From 74b04a01b71feddabe49b31d752556fa1583ee23 Mon Sep 17 00:00:00 2001 From: Ximin Luo Date: Sun, 26 Apr 2020 15:13:23 +0100 Subject: [PATCH] New upstream version 1.43.0+dfsg1 --- CONTRIBUTING.md | 3 + Cargo.lock | 606 +- Cargo.toml | 7 - RELEASES.md | 162 +- config.toml.example | 16 +- git-commit-hash | 2 +- src/bootstrap/bin/rustc.rs | 11 +- src/bootstrap/bin/rustdoc.rs | 2 +- src/bootstrap/bootstrap.py | 17 +- src/bootstrap/builder.rs | 79 +- src/bootstrap/builder/tests.rs | 1 - src/bootstrap/channel.rs | 2 +- src/bootstrap/compile.rs | 22 +- src/bootstrap/config.rs | 28 +- src/bootstrap/configure.py | 18 +- src/bootstrap/dist.rs | 16 +- src/bootstrap/doc.rs | 2 +- src/bootstrap/flags.rs | 4 +- src/bootstrap/format.rs | 13 +- src/bootstrap/install.rs | 5 +- src/bootstrap/lib.rs | 23 +- src/bootstrap/metadata.rs | 1 - src/bootstrap/native.rs | 28 +- src/bootstrap/sanity.rs | 9 +- src/bootstrap/test.rs | 125 +- src/bootstrap/tool.rs | 2 +- src/bootstrap/toolstate.rs | 202 +- src/bootstrap/util.rs | 2 +- src/ci/azure-pipelines/try.yml | 2 +- src/ci/cpu-usage-over-time.py | 6 +- src/ci/docker/dist-various-2/Dockerfile | 2 +- src/ci/docker/x86_64-gnu-tools/checktools.sh | 2 +- src/ci/scripts/install-msys2-packages.sh | 5 +- src/doc/book/.cargo/config | 3 + src/doc/book/.travis.yml | 2 +- .../2018-edition/src/ch18-02-refutability.md | 2 +- src/doc/book/ADMIN_TASKS.md | 109 + src/doc/book/Cargo.lock | 251 +- src/doc/book/Cargo.toml | 20 +- src/doc/book/README.md | 14 - src/doc/book/ci/dictionary.txt | 5 + .../listing-02-01/Cargo.lock | 6 + .../listing-02-01/Cargo.toml | 9 + .../listing-02-01/src/main.rs | 31 + .../listing-02-02/Cargo.lock | 87 + .../listing-02-02/Cargo.toml | 10 + .../listing-02-02/src/main.rs | 15 + .../listing-02-03/Cargo.lock | 87 + .../listing-02-03/Cargo.toml | 10 + .../listing-02-03/src/main.rs | 28 + .../listing-02-04/Cargo.lock | 87 + .../listing-02-04/Cargo.toml | 10 + .../listing-02-04/output.txt | 21 + .../listing-02-04/src/main.rs | 32 + .../listing-02-05/Cargo.lock | 87 + .../listing-02-05/Cargo.toml | 10 + .../listing-02-05/src/main.rs | 45 + .../listing-02-06/Cargo.lock | 87 + .../listing-02-06/Cargo.toml | 10 + .../listing-02-06/src/main.rs | 35 + .../no-listing-01-cargo-new/Cargo.lock | 6 + .../no-listing-01-cargo-new/Cargo.toml | 9 + .../no-listing-01-cargo-new/output.txt | 5 + .../no-listing-01-cargo-new/src/main.rs | 3 + .../no-listing-02-without-expect/Cargo.lock | 6 + .../no-listing-02-without-expect/Cargo.toml | 9 + .../no-listing-02-without-expect/output.txt | 12 + .../no-listing-02-without-expect/src/main.rs | 13 + .../Cargo.lock | 87 + .../Cargo.toml | 10 + .../src/main.rs | 33 + .../no-listing-04-looping/Cargo.lock | 87 + .../no-listing-04-looping/Cargo.toml | 10 + .../no-listing-04-looping/src/main.rs | 40 + .../no-listing-05-quitting/Cargo.lock | 87 + .../no-listing-05-quitting/Cargo.toml | 10 + .../no-listing-05-quitting/src/main.rs | 38 + .../listing-03-01/Cargo.lock | 6 + .../listing-03-01/Cargo.toml | 7 + .../listing-03-01/src/main.rs | 3 + .../listing-03-02/Cargo.lock | 6 + .../listing-03-02/Cargo.toml | 7 + .../listing-03-02/output.txt | 5 + .../listing-03-02/src/main.rs | 6 + .../listing-03-03/Cargo.lock | 6 + .../listing-03-03/Cargo.toml | 7 + .../listing-03-03/src/main.rs | 11 + .../listing-03-04/Cargo.lock | 6 + .../listing-03-04/Cargo.toml | 7 + .../listing-03-04/output.txt | 9 + .../listing-03-04/src/main.rs | 10 + .../listing-03-05/Cargo.lock | 6 + .../listing-03-05/Cargo.toml | 7 + .../listing-03-05/src/main.rs | 7 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 20 + .../src/main.rs | 6 + .../no-listing-02-adding-mut/Cargo.lock | 6 + .../no-listing-02-adding-mut/Cargo.toml | 7 + .../no-listing-02-adding-mut/output.txt | 6 + .../no-listing-02-adding-mut/src/main.rs | 6 + .../no-listing-03-shadowing/Cargo.lock | 6 + .../no-listing-03-shadowing/Cargo.toml | 7 + .../no-listing-03-shadowing/output.txt | 5 + .../no-listing-03-shadowing/src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 14 + .../src/main.rs | 6 + .../no-listing-06-floating-point/Cargo.lock | 6 + .../no-listing-06-floating-point/Cargo.toml | 7 + .../no-listing-06-floating-point/src/main.rs | 5 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 16 + .../no-listing-08-boolean/Cargo.lock | 6 + .../no-listing-08-boolean/Cargo.toml | 7 + .../no-listing-08-boolean/src/main.rs | 5 + .../no-listing-09-char/Cargo.lock | 6 + .../no-listing-09-char/Cargo.toml | 7 + .../no-listing-09-char/src/main.rs | 5 + .../no-listing-10-tuples/Cargo.lock | 6 + .../no-listing-10-tuples/Cargo.toml | 7 + .../no-listing-10-tuples/src/main.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 7 + .../no-listing-12-tuple-indexing/Cargo.lock | 6 + .../no-listing-12-tuple-indexing/Cargo.toml | 7 + .../no-listing-12-tuple-indexing/src/main.rs | 9 + .../no-listing-13-arrays/Cargo.lock | 6 + .../no-listing-13-arrays/Cargo.toml | 7 + .../no-listing-13-arrays/src/main.rs | 3 + .../no-listing-14-array-indexing/Cargo.lock | 6 + .../no-listing-14-array-indexing/Cargo.toml | 7 + .../no-listing-14-array-indexing/src/main.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 6 + .../src/main.rs | 8 + .../no-listing-16-functions/Cargo.lock | 6 + .../no-listing-16-functions/Cargo.toml | 7 + .../no-listing-16-functions/output.txt | 6 + .../no-listing-16-functions/src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 5 + .../src/main.rs | 7 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 6 + .../src/main.rs | 8 + .../Cargo.lock | 4 + .../Cargo.toml | 7 + .../rustfmt-ignore | 1 + .../src/main.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 10 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 5 + .../src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 18 + .../src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 4 + .../no-listing-26-if-true/Cargo.lock | 6 + .../no-listing-26-if-true/Cargo.toml | 7 + .../no-listing-26-if-true/output.txt | 5 + .../no-listing-26-if-true/src/main.rs | 9 + .../no-listing-27-if-false/Cargo.lock | 6 + .../no-listing-27-if-false/Cargo.toml | 7 + .../no-listing-27-if-false/output.txt | 5 + .../no-listing-27-if-false/src/main.rs | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 14 + .../src/main.rs | 7 + .../no-listing-29-if-not-equal-0/Cargo.lock | 6 + .../no-listing-29-if-not-equal-0/Cargo.toml | 7 + .../no-listing-29-if-not-equal-0/src/main.rs | 7 + .../no-listing-30-else-if/Cargo.lock | 6 + .../no-listing-30-else-if/Cargo.toml | 7 + .../no-listing-30-else-if/output.txt | 5 + .../no-listing-30-else-if/src/main.rs | 13 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/main.rs | 7 + .../no-listing-32-loop/Cargo.lock | 6 + .../no-listing-32-loop/Cargo.toml | 7 + .../no-listing-32-loop/src/main.rs | 5 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 13 + .../no-listing-34-for-range/Cargo.lock | 6 + .../no-listing-34-for-range/Cargo.toml | 7 + .../no-listing-34-for-range/src/main.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 9 + .../output.txt | 14 + .../src/main.rs | 3 + .../listing-04-01/Cargo.lock | 4 + .../listing-04-01/Cargo.toml | 7 + .../listing-04-01/rustfmt-ignore | 3 + .../listing-04-01/src/main.rs | 9 + .../listing-04-02/Cargo.lock | 6 + .../listing-04-02/Cargo.toml | 7 + .../listing-04-02/src/main.rs | 6 + .../listing-04-03/Cargo.lock | 4 + .../listing-04-03/Cargo.toml | 7 + .../listing-04-03/rustfmt-ignore | 3 + .../listing-04-03/src/main.rs | 23 + .../listing-04-04/Cargo.lock | 4 + .../listing-04-04/Cargo.toml | 7 + .../listing-04-04/rustfmt-ignore | 3 + .../listing-04-04/src/main.rs | 29 + .../listing-04-05/Cargo.lock | 6 + .../listing-04-05/Cargo.toml | 7 + .../listing-04-05/src/main.rs | 13 + .../listing-04-06/Cargo.lock | 6 + .../listing-04-06/Cargo.toml | 7 + .../listing-04-06/output.txt | 16 + .../listing-04-06/src/main.rs | 9 + .../listing-04-07/Cargo.lock | 6 + .../listing-04-07/Cargo.toml | 7 + .../listing-04-07/src/main.rs | 21 + .../listing-04-08/Cargo.lock | 6 + .../listing-04-08/Cargo.toml | 7 + .../listing-04-08/src/main.rs | 24 + .../listing-04-09/Cargo.lock | 6 + .../listing-04-09/Cargo.toml | 7 + .../listing-04-09/src/main.rs | 31 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 9 + .../no-listing-02-string-scope/Cargo.lock | 4 + .../no-listing-02-string-scope/Cargo.toml | 7 + .../no-listing-02-string-scope/rustfmt-ignore | 3 + .../no-listing-02-string-scope/src/main.rs | 10 + .../no-listing-03-string-move/Cargo.lock | 6 + .../no-listing-03-string-move/Cargo.toml | 7 + .../no-listing-03-string-move/src/main.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 19 + .../src/main.rs | 8 + .../no-listing-05-clone/Cargo.lock | 6 + .../no-listing-05-clone/Cargo.toml | 7 + .../no-listing-05-clone/src/main.rs | 8 + .../no-listing-06-copy/Cargo.lock | 6 + .../no-listing-06-copy/Cargo.toml | 7 + .../no-listing-06-copy/src/main.rs | 8 + .../no-listing-07-reference/Cargo.lock | 6 + .../no-listing-07-reference/Cargo.toml | 7 + .../no-listing-07-reference/src/main.rs | 15 + .../Cargo.lock | 4 + .../Cargo.toml | 7 + .../rustfmt-ignore | 3 + .../src/main.rs | 14 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 19 + .../src/main.rs | 10 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 20 + .../src/main.rs | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 13 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/main.rs | 9 + .../Cargo.lock | 4 + .../Cargo.toml | 7 + .../rustfmt-ignore | 3 + .../src/main.rs | 13 + .../no-listing-16-no-dangle/Cargo.lock | 6 + .../no-listing-16-no-dangle/Cargo.toml | 7 + .../no-listing-16-no-dangle/src/main.rs | 11 + .../no-listing-17-slice/Cargo.lock | 6 + .../no-listing-17-slice/Cargo.toml | 7 + .../no-listing-17-slice/src/main.rs | 8 + .../no-listing-18-first-word-slice/Cargo.lock | 6 + .../no-listing-18-first-word-slice/Cargo.toml | 7 + .../src/main.rs | 15 + .../no-listing-19-slice-error/Cargo.lock | 6 + .../no-listing-19-slice-error/Cargo.toml | 7 + .../no-listing-19-slice-error/output.txt | 20 + .../no-listing-19-slice-error/src/main.rs | 23 + .../listing-05-01/Cargo.lock | 6 + .../listing-05-01/Cargo.toml | 7 + .../listing-05-01/src/main.rs | 10 + .../listing-05-02/Cargo.lock | 6 + .../listing-05-02/Cargo.toml | 7 + .../listing-05-02/src/main.rs | 17 + .../listing-05-03/Cargo.lock | 6 + .../listing-05-03/Cargo.toml | 7 + .../listing-05-03/src/main.rs | 19 + .../listing-05-04/Cargo.lock | 6 + .../listing-05-04/Cargo.toml | 7 + .../listing-05-04/src/main.rs | 24 + .../listing-05-05/Cargo.lock | 6 + .../listing-05-05/Cargo.toml | 7 + .../listing-05-05/src/main.rs | 24 + .../listing-05-06/Cargo.lock | 6 + .../listing-05-06/Cargo.toml | 7 + .../listing-05-06/src/main.rs | 24 + .../listing-05-07/Cargo.lock | 6 + .../listing-05-07/Cargo.toml | 7 + .../listing-05-07/src/main.rs | 23 + .../listing-05-08/Cargo.lock | 6 + .../listing-05-08/Cargo.toml | 7 + .../listing-05-08/output.txt | 5 + .../listing-05-08/src/main.rs | 17 + .../listing-05-09/Cargo.lock | 6 + .../listing-05-09/Cargo.toml | 7 + .../listing-05-09/src/main.rs | 12 + .../listing-05-10/Cargo.lock | 6 + .../listing-05-10/Cargo.toml | 7 + .../listing-05-10/src/main.rs | 20 + .../listing-05-11/Cargo.lock | 6 + .../listing-05-11/Cargo.toml | 7 + .../listing-05-11/output.txt | 18 + .../listing-05-11/src/main.rs | 13 + .../listing-05-12/Cargo.lock | 6 + .../listing-05-12/Cargo.toml | 7 + .../listing-05-12/output.txt | 5 + .../listing-05-12/src/main.rs | 14 + .../listing-05-13/Cargo.lock | 6 + .../listing-05-13/Cargo.toml | 7 + .../listing-05-13/src/main.rs | 23 + .../listing-05-14/Cargo.lock | 6 + .../listing-05-14/Cargo.toml | 7 + .../listing-05-14/src/main.rs | 17 + .../listing-05-15/Cargo.lock | 6 + .../listing-05-15/Cargo.toml | 7 + .../listing-05-15/src/main.rs | 35 + .../listing-05-16/Cargo.lock | 6 + .../listing-05-16/Cargo.toml | 7 + .../listing-05-16/src/main.rs | 37 + .../no-listing-01-tuple-structs/Cargo.lock | 6 + .../no-listing-01-tuple-structs/Cargo.toml | 7 + .../no-listing-01-tuple-structs/src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 9 + .../output.txt | 20 + .../src/main.rs | 15 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 20 + .../output-only-01-debug/Cargo.lock | 6 + .../output-only-01-debug/Cargo.toml | 7 + .../output-only-01-debug/output.txt | 18 + .../output-only-01-debug/src/main.rs | 13 + .../output-only-02-pretty-debug/Cargo.lock | 6 + .../output-only-02-pretty-debug/Cargo.toml | 7 + .../output-only-02-pretty-debug/output.txt | 8 + .../output-only-02-pretty-debug/src/main.rs | 14 + .../listing-06-01/Cargo.lock | 6 + .../listing-06-01/Cargo.toml | 7 + .../listing-06-01/src/main.rs | 23 + .../listing-06-02/Cargo.lock | 6 + .../listing-06-02/Cargo.toml | 7 + .../listing-06-02/src/main.rs | 10 + .../listing-06-03/Cargo.lock | 6 + .../listing-06-03/Cargo.toml | 7 + .../listing-06-03/src/main.rs | 19 + .../listing-06-04/Cargo.lock | 6 + .../listing-06-04/Cargo.toml | 7 + .../listing-06-04/src/main.rs | 17 + .../listing-06-05/Cargo.lock | 6 + .../listing-06-05/Cargo.toml | 7 + .../listing-06-05/src/main.rs | 18 + .../listing-06-06/Cargo.lock | 6 + .../listing-06-06/Cargo.toml | 7 + .../listing-06-06/src/main.rs | 9 + .../no-listing-01-defining-enums/Cargo.lock | 6 + .../no-listing-01-defining-enums/Cargo.toml | 7 + .../no-listing-01-defining-enums/src/main.rs | 22 + .../no-listing-02-enum-with-data/Cargo.lock | 6 + .../no-listing-02-enum-with-data/Cargo.toml | 7 + .../no-listing-02-enum-with-data/src/main.rs | 12 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 12 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 11 + .../no-listing-05-methods-on-enums/Cargo.lock | 6 + .../no-listing-05-methods-on-enums/Cargo.toml | 7 + .../src/main.rs | 19 + .../no-listing-06-option-examples/Cargo.lock | 6 + .../no-listing-06-option-examples/Cargo.toml | 7 + .../no-listing-06-option-examples/src/main.rs | 8 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/main.rs | 8 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 22 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 31 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/main.rs | 13 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 12 + .../no-listing-12-if-let/Cargo.lock | 6 + .../no-listing-12-if-let/Cargo.toml | 7 + .../no-listing-12-if-let/src/main.rs | 8 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 24 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 25 + .../listing-07-01/Cargo.lock | 6 + .../listing-07-01/Cargo.toml | 7 + .../listing-07-01/src/lib.rs | 19 + .../listing-07-03/Cargo.lock | 6 + .../listing-07-03/Cargo.toml | 7 + .../listing-07-03/output.txt | 20 + .../listing-07-03/src/lib.rs | 13 + .../listing-07-05/Cargo.lock | 6 + .../listing-07-05/Cargo.toml | 7 + .../listing-07-05/output.txt | 20 + .../listing-07-05/src/lib.rs | 13 + .../listing-07-07/Cargo.lock | 6 + .../listing-07-07/Cargo.toml | 7 + .../listing-07-07/src/lib.rs | 17 + .../listing-07-08/Cargo.lock | 6 + .../listing-07-08/Cargo.toml | 7 + .../listing-07-08/src/lib.rs | 14 + .../listing-07-09/Cargo.lock | 6 + .../listing-07-09/Cargo.toml | 7 + .../listing-07-09/src/lib.rs | 27 + .../listing-07-10/Cargo.lock | 6 + .../listing-07-10/Cargo.toml | 7 + .../listing-07-10/src/lib.rs | 11 + .../listing-07-11/Cargo.lock | 6 + .../listing-07-11/Cargo.toml | 7 + .../listing-07-11/src/lib.rs | 17 + .../listing-07-12/Cargo.lock | 6 + .../listing-07-12/Cargo.toml | 7 + .../listing-07-12/src/lib.rs | 17 + .../listing-07-13/Cargo.lock | 6 + .../listing-07-13/Cargo.toml | 7 + .../listing-07-13/src/lib.rs | 17 + .../listing-07-14/Cargo.lock | 6 + .../listing-07-14/Cargo.toml | 7 + .../listing-07-14/src/main.rs | 6 + .../listing-07-15/Cargo.lock | 6 + .../listing-07-15/Cargo.toml | 7 + .../listing-07-15/src/lib.rs | 18 + .../listing-07-16/Cargo.lock | 6 + .../listing-07-16/Cargo.toml | 7 + .../listing-07-16/src/lib.rs | 18 + .../listing-07-17/Cargo.lock | 6 + .../listing-07-17/Cargo.toml | 7 + .../listing-07-17/src/lib.rs | 17 + .../listing-07-18/Cargo.lock | 87 + .../listing-07-18/Cargo.toml | 8 + .../listing-07-18/src/main.rs | 32 + .../listing-07-19/Cargo.lock | 6 + .../listing-07-19/Cargo.toml | 7 + .../listing-07-19/src/lib.rs | 2 + .../listing-07-20/Cargo.lock | 6 + .../listing-07-20/Cargo.toml | 7 + .../listing-07-20/src/lib.rs | 1 + .../listing-07-21-and-22/Cargo.lock | 6 + .../listing-07-21-and-22/Cargo.toml | 7 + .../src/front_of_house.rs | 3 + .../listing-07-21-and-22/src/lib.rs | 9 + .../no-listing-01-use-std-unnested/Cargo.lock | 87 + .../no-listing-01-use-std-unnested/Cargo.toml | 10 + .../src/main.rs | 31 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/front_of_house.rs | 1 + .../src/front_of_house/hosting.rs | 1 + .../src/lib.rs | 9 + .../listing-08-01/Cargo.lock | 6 + .../listing-08-01/Cargo.toml | 7 + .../listing-08-01/src/main.rs | 5 + .../listing-08-02/Cargo.lock | 6 + .../listing-08-02/Cargo.toml | 7 + .../listing-08-02/src/main.rs | 5 + .../listing-08-03/Cargo.lock | 6 + .../listing-08-03/Cargo.toml | 7 + .../listing-08-03/src/main.rs | 10 + .../listing-08-04/Cargo.lock | 6 + .../listing-08-04/Cargo.toml | 7 + .../listing-08-04/src/main.rs | 9 + .../listing-08-05/Cargo.lock | 6 + .../listing-08-05/Cargo.toml | 7 + .../listing-08-05/src/main.rs | 13 + .../listing-08-06/Cargo.lock | 6 + .../listing-08-06/Cargo.toml | 7 + .../listing-08-06/src/main.rs | 8 + .../listing-08-07/Cargo.lock | 6 + .../listing-08-07/Cargo.toml | 7 + .../listing-08-07/output.txt | 20 + .../listing-08-07/src/main.rs | 11 + .../listing-08-08/Cargo.lock | 6 + .../listing-08-08/Cargo.toml | 7 + .../listing-08-08/src/main.rs | 8 + .../listing-08-09/Cargo.lock | 6 + .../listing-08-09/Cargo.toml | 7 + .../listing-08-09/src/main.rs | 8 + .../listing-08-10/Cargo.lock | 6 + .../listing-08-10/Cargo.toml | 7 + .../listing-08-10/src/main.rs | 15 + .../listing-08-11/Cargo.lock | 6 + .../listing-08-11/Cargo.toml | 7 + .../listing-08-11/src/main.rs | 5 + .../listing-08-12/Cargo.lock | 6 + .../listing-08-12/Cargo.toml | 7 + .../listing-08-12/src/main.rs | 10 + .../listing-08-13/Cargo.lock | 6 + .../listing-08-13/Cargo.toml | 7 + .../listing-08-13/src/main.rs | 5 + .../listing-08-14/Cargo.lock | 6 + .../listing-08-14/Cargo.toml | 7 + .../listing-08-14/src/main.rs | 19 + .../listing-08-15/Cargo.lock | 6 + .../listing-08-15/Cargo.toml | 7 + .../listing-08-15/src/main.rs | 6 + .../listing-08-16/Cargo.lock | 6 + .../listing-08-16/Cargo.toml | 7 + .../listing-08-16/src/main.rs | 8 + .../listing-08-17/Cargo.lock | 6 + .../listing-08-17/Cargo.toml | 7 + .../listing-08-17/src/main.rs | 6 + .../listing-08-18/Cargo.lock | 6 + .../listing-08-18/Cargo.toml | 7 + .../listing-08-18/src/main.rs | 7 + .../listing-08-19/Cargo.lock | 6 + .../listing-08-19/Cargo.toml | 7 + .../listing-08-19/output.txt | 16 + .../listing-08-19/src/main.rs | 6 + .../listing-08-20/Cargo.lock | 6 + .../listing-08-20/Cargo.toml | 7 + .../listing-08-20/src/main.rs | 10 + .../listing-08-21/Cargo.lock | 6 + .../listing-08-21/Cargo.toml | 7 + .../listing-08-21/src/main.rs | 11 + .../listing-08-22/Cargo.lock | 6 + .../listing-08-22/Cargo.toml | 7 + .../listing-08-22/src/main.rs | 13 + .../listing-08-23/Cargo.lock | 6 + .../listing-08-23/Cargo.toml | 7 + .../listing-08-23/src/main.rs | 13 + .../listing-08-24/Cargo.lock | 6 + .../listing-08-24/Cargo.toml | 7 + .../listing-08-24/src/main.rs | 12 + .../listing-08-25/Cargo.lock | 6 + .../listing-08-25/Cargo.toml | 7 + .../listing-08-25/src/main.rs | 13 + .../listing-08-26/Cargo.lock | 6 + .../listing-08-26/Cargo.toml | 7 + .../listing-08-26/src/main.rs | 16 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 9 + .../no-listing-02-format/Cargo.lock | 6 + .../no-listing-02-format/Cargo.toml | 7 + .../no-listing-02-format/src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 14 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 6 + .../src/main.rs | 5 + .../listing-09-01/Cargo.lock | 6 + .../listing-09-01/Cargo.toml | 7 + .../listing-09-01/output.txt | 6 + .../listing-09-01/src/main.rs | 5 + .../listing-09-03/Cargo.lock | 6 + .../listing-09-03/Cargo.toml | 7 + .../listing-09-03/src/main.rs | 5 + .../listing-09-04/Cargo.lock | 6 + .../listing-09-04/Cargo.toml | 7 + .../listing-09-04/output.txt | 6 + .../listing-09-04/src/main.rs | 10 + .../listing-09-05/Cargo.lock | 6 + .../listing-09-05/Cargo.toml | 7 + .../listing-09-05/src/main.rs | 19 + .../listing-09-06/Cargo.lock | 6 + .../listing-09-06/Cargo.toml | 7 + .../listing-09-06/src/main.rs | 25 + .../listing-09-07/Cargo.lock | 6 + .../listing-09-07/Cargo.toml | 7 + .../listing-09-07/src/main.rs | 16 + .../listing-09-08/Cargo.lock | 6 + .../listing-09-08/Cargo.toml | 7 + .../listing-09-08/src/main.rs | 17 + .../listing-09-09/Cargo.lock | 6 + .../listing-09-09/Cargo.toml | 7 + .../listing-09-09/src/main.rs | 12 + .../listing-09-10/Cargo.lock | 87 + .../listing-09-10/Cargo.toml | 8 + .../listing-09-10/src/main.rs | 55 + .../no-listing-01-panic/Cargo.lock | 6 + .../no-listing-01-panic/Cargo.toml | 7 + .../no-listing-01-panic/output.txt | 6 + .../no-listing-01-panic/src/main.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 19 + .../src/main.rs | 7 + .../no-listing-03-closures/Cargo.lock | 6 + .../no-listing-03-closures/Cargo.toml | 7 + .../no-listing-03-closures/src/main.rs | 14 + .../no-listing-04-unwrap/Cargo.lock | 6 + .../no-listing-04-unwrap/Cargo.toml | 7 + .../no-listing-04-unwrap/src/main.rs | 5 + .../no-listing-05-expect/Cargo.lock | 6 + .../no-listing-05-expect/Cargo.toml | 7 + .../no-listing-05-expect/src/main.rs | 5 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 20 + .../src/main.rs | 5 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 8 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 7 + .../Cargo.lock | 87 + .../Cargo.toml | 8 + .../src/main.rs | 47 + .../listing-10-01/Cargo.lock | 6 + .../listing-10-01/Cargo.toml | 7 + .../listing-10-01/src/main.rs | 18 + .../listing-10-02/Cargo.lock | 6 + .../listing-10-02/Cargo.toml | 7 + .../listing-10-02/src/main.rs | 25 + .../listing-10-03/Cargo.lock | 6 + .../listing-10-03/Cargo.toml | 7 + .../listing-10-03/src/main.rs | 31 + .../listing-10-04/Cargo.lock | 6 + .../listing-10-04/Cargo.toml | 7 + .../listing-10-04/src/main.rs | 43 + .../listing-10-05/Cargo.lock | 6 + .../listing-10-05/Cargo.toml | 7 + .../listing-10-05/output.txt | 18 + .../listing-10-05/src/main.rs | 23 + .../listing-10-06/Cargo.lock | 6 + .../listing-10-06/Cargo.toml | 7 + .../listing-10-06/src/main.rs | 9 + .../listing-10-07/Cargo.lock | 6 + .../listing-10-07/Cargo.toml | 7 + .../listing-10-07/output.txt | 14 + .../listing-10-07/src/main.rs | 8 + .../listing-10-08/Cargo.lock | 6 + .../listing-10-08/Cargo.toml | 7 + .../listing-10-08/src/main.rs | 10 + .../listing-10-09/Cargo.lock | 6 + .../listing-10-09/Cargo.toml | 7 + .../listing-10-09/src/main.rs | 16 + .../listing-10-10/Cargo.lock | 6 + .../listing-10-10/Cargo.toml | 7 + .../listing-10-10/src/main.rs | 24 + .../listing-10-11/Cargo.lock | 6 + .../listing-10-11/Cargo.toml | 7 + .../listing-10-11/src/main.rs | 22 + .../listing-10-12/Cargo.lock | 6 + .../listing-10-12/Cargo.toml | 7 + .../listing-10-12/src/lib.rs | 3 + .../listing-10-13/Cargo.lock | 6 + .../listing-10-13/Cargo.toml | 7 + .../listing-10-13/src/lib.rs | 31 + .../listing-10-14/Cargo.lock | 6 + .../listing-10-14/Cargo.toml | 7 + .../listing-10-14/src/lib.rs | 29 + .../listing-10-15/Cargo.lock | 6 + .../listing-10-15/Cargo.toml | 7 + .../listing-10-15/src/main.rs | 23 + .../listing-10-16/Cargo.lock | 6 + .../listing-10-16/Cargo.toml | 7 + .../listing-10-16/src/lib.rs | 22 + .../listing-10-17/Cargo.lock | 6 + .../listing-10-17/Cargo.toml | 7 + .../listing-10-17/output.txt | 19 + .../listing-10-17/src/main.rs | 14 + .../listing-10-18/Cargo.lock | 4 + .../listing-10-18/Cargo.toml | 7 + .../listing-10-18/rustfmt-ignore | 3 + .../listing-10-18/src/main.rs | 14 + .../listing-10-19/Cargo.lock | 4 + .../listing-10-19/Cargo.toml | 7 + .../listing-10-19/rustfmt-ignore | 3 + .../listing-10-19/src/main.rs | 12 + .../listing-10-20/Cargo.lock | 6 + .../listing-10-20/Cargo.toml | 7 + .../listing-10-20/src/main.rs | 7 + .../listing-10-21/Cargo.lock | 6 + .../listing-10-21/Cargo.toml | 7 + .../listing-10-21/output.txt | 16 + .../listing-10-21/src/main.rs | 17 + .../listing-10-22/Cargo.lock | 6 + .../listing-10-22/Cargo.toml | 7 + .../listing-10-22/src/main.rs | 17 + .../listing-10-23/Cargo.lock | 6 + .../listing-10-23/Cargo.toml | 7 + .../listing-10-23/src/main.rs | 19 + .../listing-10-24/Cargo.lock | 6 + .../listing-10-24/Cargo.toml | 7 + .../listing-10-24/output.txt | 18 + .../listing-10-24/src/main.rs | 19 + .../listing-10-25/Cargo.lock | 6 + .../listing-10-25/Cargo.toml | 7 + .../listing-10-25/src/main.rs | 11 + .../listing-10-26/Cargo.lock | 6 + .../listing-10-26/Cargo.toml | 7 + .../listing-10-26/src/main.rs | 29 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 29 + .../src/main.rs | 16 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 27 + .../src/main.rs | 17 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 24 + .../src/main.rs | 16 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 35 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 42 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 56 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 29 + .../src/main.rs | 25 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 13 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 17 + .../src/main.rs | 14 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 28 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 31 + .../listing-11-01/Cargo.lock | 6 + .../listing-11-01/Cargo.toml | 7 + .../listing-11-01/output.txt | 16 + .../listing-11-01/src/lib.rs | 11 + .../listing-11-03/Cargo.lock | 6 + .../listing-11-03/Cargo.toml | 7 + .../listing-11-03/output.txt | 22 + .../listing-11-03/src/lib.rs | 16 + .../listing-11-05/Cargo.lock | 6 + .../listing-11-05/Cargo.toml | 7 + .../listing-11-05/src/lib.rs | 15 + .../listing-11-06/Cargo.lock | 6 + .../listing-11-06/Cargo.toml | 7 + .../listing-11-06/output.txt | 16 + .../listing-11-06/src/lib.rs | 34 + .../listing-11-07/Cargo.lock | 6 + .../listing-11-07/Cargo.toml | 7 + .../listing-11-07/output.txt | 16 + .../listing-11-07/src/lib.rs | 17 + .../listing-11-08/Cargo.lock | 6 + .../listing-11-08/Cargo.toml | 7 + .../listing-11-08/output.txt | 16 + .../listing-11-08/src/lib.rs | 28 + .../listing-11-09/Cargo.lock | 6 + .../listing-11-09/Cargo.toml | 7 + .../listing-11-09/src/lib.rs | 37 + .../listing-11-10/Cargo.lock | 6 + .../listing-11-10/Cargo.toml | 7 + .../listing-11-10/output.txt | 25 + .../listing-11-10/src/lib.rs | 21 + .../listing-11-11/Cargo.lock | 6 + .../listing-11-11/Cargo.toml | 7 + .../listing-11-11/output.txt | 18 + .../listing-11-11/src/lib.rs | 23 + .../listing-11-12/Cargo.lock | 6 + .../listing-11-12/Cargo.toml | 7 + .../listing-11-12/src/lib.rs | 21 + .../listing-11-13/Cargo.lock | 6 + .../listing-11-13/Cargo.toml | 7 + .../listing-11-13/output.txt | 23 + .../listing-11-13/src/lib.rs | 17 + .../listing-11-13/tests/integration_test.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/lib.rs | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 17 + .../src/lib.rs | 51 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 22 + .../src/lib.rs | 49 + .../no-listing-04-bug-in-add-two/Cargo.lock | 6 + .../no-listing-04-bug-in-add-two/Cargo.toml | 7 + .../no-listing-04-bug-in-add-two/output.txt | 23 + .../no-listing-04-bug-in-add-two/src/lib.rs | 17 + .../no-listing-05-greeter/Cargo.lock | 6 + .../no-listing-05-greeter/Cargo.toml | 7 + .../no-listing-05-greeter/src/lib.rs | 18 + .../no-listing-06-greeter-with-bug/Cargo.lock | 6 + .../no-listing-06-greeter-with-bug/Cargo.toml | 7 + .../no-listing-06-greeter-with-bug/output.txt | 21 + .../no-listing-06-greeter-with-bug/src/lib.rs | 18 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 21 + .../src/lib.rs | 20 + .../no-listing-08-guess-with-bug/Cargo.lock | 6 + .../no-listing-08-guess-with-bug/Cargo.toml | 7 + .../no-listing-08-guess-with-bug/output.txt | 19 + .../no-listing-08-guess-with-bug/src/lib.rs | 29 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 23 + .../src/lib.rs | 34 + .../no-listing-10-result-in-tests/Cargo.lock | 6 + .../no-listing-10-result-in-tests/Cargo.toml | 7 + .../no-listing-10-result-in-tests/src/lib.rs | 11 + .../no-listing-11-ignore-a-test/Cargo.lock | 6 + .../no-listing-11-ignore-a-test/Cargo.toml | 7 + .../no-listing-11-ignore-a-test/output.txt | 17 + .../no-listing-11-ignore-a-test/src/lib.rs | 14 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 29 + .../src/lib.rs | 17 + .../tests/common.rs | 3 + .../tests/integration_test.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 17 + .../tests/common/mod.rs | 3 + .../tests/integration_test.rs | 9 + .../output-only-01-show-output/Cargo.lock | 6 + .../output-only-01-show-output/Cargo.toml | 7 + .../output-only-01-show-output/output.txt | 34 + .../output-only-01-show-output/src/lib.rs | 21 + .../output-only-02-single-test/Cargo.lock | 6 + .../output-only-02-single-test/Cargo.toml | 7 + .../output-only-02-single-test/output.txt | 10 + .../output-only-02-single-test/src/lib.rs | 23 + .../output-only-03-multiple-tests/Cargo.lock | 6 + .../output-only-03-multiple-tests/Cargo.toml | 7 + .../output-only-03-multiple-tests/output.txt | 11 + .../output-only-03-multiple-tests/src/lib.rs | 23 + .../output-only-04-running-ignored/Cargo.lock | 6 + .../output-only-04-running-ignored/Cargo.toml | 7 + .../output-only-04-running-ignored/output.txt | 16 + .../output-only-04-running-ignored/src/lib.rs | 14 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 10 + .../src/lib.rs | 17 + .../tests/integration_test.rs | 6 + .../listing-12-01/Cargo.lock | 6 + .../listing-12-01/Cargo.toml | 7 + .../listing-12-01/output.txt | 5 + .../listing-12-01/src/main.rs | 6 + .../listing-12-02/Cargo.lock | 6 + .../listing-12-02/Cargo.toml | 7 + .../listing-12-02/output.txt | 6 + .../listing-12-02/src/main.rs | 11 + .../listing-12-03/Cargo.lock | 6 + .../listing-12-03/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-03/poem.txt | 9 + .../listing-12-03/src/main.rs | 11 + .../listing-12-04/Cargo.lock | 6 + .../listing-12-04/Cargo.toml | 7 + .../listing-12-04/output.txt | 17 + .../ch12-an-io-project/listing-12-04/poem.txt | 9 + .../listing-12-04/src/main.rs | 22 + .../listing-12-05/Cargo.lock | 6 + .../listing-12-05/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-05/poem.txt | 9 + .../listing-12-05/src/main.rs | 29 + .../listing-12-06/Cargo.lock | 6 + .../listing-12-06/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-06/poem.txt | 9 + .../listing-12-06/src/main.rs | 34 + .../listing-12-07/Cargo.lock | 6 + .../listing-12-07/Cargo.toml | 7 + .../listing-12-07/output.txt | 6 + .../ch12-an-io-project/listing-12-07/poem.txt | 9 + .../listing-12-07/src/main.rs | 40 + .../listing-12-08/Cargo.lock | 6 + .../listing-12-08/Cargo.toml | 7 + .../listing-12-08/output.txt | 6 + .../ch12-an-io-project/listing-12-08/poem.txt | 9 + .../listing-12-08/src/main.rs | 38 + .../listing-12-09/Cargo.lock | 6 + .../listing-12-09/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-09/poem.txt | 9 + .../listing-12-09/src/main.rs | 36 + .../listing-12-10/Cargo.lock | 6 + .../listing-12-10/Cargo.toml | 7 + .../listing-12-10/output.txt | 5 + .../ch12-an-io-project/listing-12-10/poem.txt | 9 + .../listing-12-10/src/main.rs | 42 + .../listing-12-11/Cargo.lock | 6 + .../listing-12-11/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-11/poem.txt | 9 + .../listing-12-11/src/main.rs | 50 + .../listing-12-12/Cargo.lock | 6 + .../listing-12-12/Cargo.toml | 7 + .../listing-12-12/output.txt | 26 + .../ch12-an-io-project/listing-12-12/poem.txt | 9 + .../listing-12-12/src/main.rs | 51 + .../listing-12-13/Cargo.lock | 6 + .../listing-12-13/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-13/poem.txt | 9 + .../listing-12-13/src/lib.rs | 36 + .../listing-12-13/src/main.rs | 20 + .../listing-12-14/Cargo.lock | 6 + .../listing-12-14/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-14/poem.txt | 9 + .../listing-12-14/src/lib.rs | 28 + .../listing-12-14/src/main.rs | 30 + .../listing-12-15/Cargo.lock | 6 + .../listing-12-15/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-15/poem.txt | 9 + .../listing-12-15/src/lib.rs | 46 + .../listing-12-15/src/main.rs | 19 + .../listing-12-16/Cargo.lock | 6 + .../listing-12-16/Cargo.toml | 7 + .../listing-12-16/output.txt | 23 + .../ch12-an-io-project/listing-12-16/poem.txt | 9 + .../listing-12-16/src/lib.rs | 50 + .../listing-12-16/src/main.rs | 19 + .../listing-12-17/Cargo.lock | 6 + .../listing-12-17/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-17/poem.txt | 9 + .../listing-12-17/src/lib.rs | 50 + .../listing-12-17/src/main.rs | 19 + .../listing-12-18/Cargo.lock | 6 + .../listing-12-18/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-18/poem.txt | 9 + .../listing-12-18/src/lib.rs | 52 + .../listing-12-18/src/main.rs | 19 + .../listing-12-19/Cargo.lock | 6 + .../listing-12-19/Cargo.toml | 7 + .../listing-12-19/output.txt | 22 + .../ch12-an-io-project/listing-12-19/poem.txt | 9 + .../listing-12-19/src/lib.rs | 58 + .../listing-12-19/src/main.rs | 19 + .../listing-12-20/Cargo.lock | 6 + .../listing-12-20/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-20/poem.txt | 9 + .../listing-12-20/src/lib.rs | 78 + .../listing-12-20/src/main.rs | 19 + .../listing-12-21/Cargo.lock | 6 + .../listing-12-21/Cargo.toml | 7 + .../listing-12-21/output.txt | 23 + .../ch12-an-io-project/listing-12-21/poem.txt | 9 + .../listing-12-21/src/lib.rs | 94 + .../listing-12-21/src/main.rs | 19 + .../listing-12-22/Cargo.lock | 6 + .../listing-12-22/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-22/poem.txt | 9 + .../listing-12-22/src/lib.rs | 103 + .../listing-12-22/src/main.rs | 19 + .../listing-12-23/Cargo.lock | 6 + .../listing-12-23/Cargo.toml | 7 + .../listing-12-23/output.txt | 6 + .../ch12-an-io-project/listing-12-23/poem.txt | 9 + .../listing-12-23/src/lib.rs | 112 + .../listing-12-23/src/main.rs | 19 + .../listing-12-24/Cargo.lock | 6 + .../listing-12-24/Cargo.toml | 7 + .../ch12-an-io-project/listing-12-24/poem.txt | 9 + .../listing-12-24/src/lib.rs | 104 + .../listing-12-24/src/main.rs | 21 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../poem.txt | 9 + .../src/main.rs | 54 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 5 + .../poem.txt | 9 + .../src/lib.rs | 60 + .../src/main.rs | 19 + .../output-only-01-with-args/Cargo.lock | 6 + .../output-only-01-with-args/Cargo.toml | 7 + .../output-only-01-with-args/output.txt | 5 + .../output-only-01-with-args/src/main.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../output-only-02-missing-lifetimes/poem.txt | 9 + .../src/lib.rs | 50 + .../src/main.rs | 19 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 7 + .../output-only-03-multiple-matches/poem.txt | 9 + .../src/lib.rs | 60 + .../src/main.rs | 19 + .../output-only-04-no-matches/Cargo.lock | 6 + .../output-only-04-no-matches/Cargo.toml | 7 + .../output-only-04-no-matches/output.txt | 4 + .../output-only-04-no-matches/poem.txt | 9 + .../output-only-04-no-matches/src/lib.rs | 60 + .../output-only-04-no-matches/src/main.rs | 19 + .../listing-12-23-reproduced/Cargo.lock | 6 + .../listing-12-23-reproduced/Cargo.toml | 7 + .../listing-12-23-reproduced/poem.txt | 9 + .../listing-12-23-reproduced/src/lib.rs | 108 + .../listing-12-23-reproduced/src/main.rs | 19 + .../listing-12-24-reproduced/Cargo.lock | 6 + .../listing-12-24-reproduced/Cargo.toml | 7 + .../listing-12-24-reproduced/poem.txt | 9 + .../listing-12-24-reproduced/src/lib.rs | 104 + .../listing-12-24-reproduced/src/main.rs | 25 + .../listing-13-01/Cargo.lock | 6 + .../listing-13-01/Cargo.toml | 7 + .../listing-13-01/src/main.rs | 12 + .../listing-13-02/Cargo.lock | 6 + .../listing-13-02/Cargo.toml | 7 + .../listing-13-02/src/main.rs | 19 + .../listing-13-03/Cargo.lock | 6 + .../listing-13-03/Cargo.toml | 7 + .../listing-13-03/src/main.rs | 39 + .../listing-13-04/Cargo.lock | 6 + .../listing-13-04/Cargo.toml | 7 + .../listing-13-04/src/main.rs | 32 + .../listing-13-05/Cargo.lock | 6 + .../listing-13-05/Cargo.toml | 7 + .../listing-13-05/src/main.rs | 33 + .../listing-13-06/Cargo.lock | 6 + .../listing-13-06/Cargo.toml | 7 + .../listing-13-06/src/main.rs | 33 + .../listing-13-07/Cargo.lock | 6 + .../listing-13-07/Cargo.toml | 7 + .../listing-13-07/src/main.rs | 33 + .../listing-13-08/Cargo.lock | 6 + .../listing-13-08/Cargo.toml | 7 + .../listing-13-08/output.txt | 17 + .../listing-13-08/src/main.rs | 8 + .../listing-13-09/Cargo.lock | 6 + .../listing-13-09/Cargo.toml | 7 + .../listing-13-09/src/main.rs | 11 + .../listing-13-10/Cargo.lock | 6 + .../listing-13-10/Cargo.toml | 7 + .../listing-13-10/src/main.rs | 34 + .../listing-13-11/Cargo.lock | 6 + .../listing-13-11/Cargo.toml | 7 + .../listing-13-11/src/main.rs | 64 + .../listing-13-12/Cargo.lock | 6 + .../listing-13-12/Cargo.toml | 7 + .../listing-13-12/src/main.rs | 9 + .../listing-13-13/Cargo.lock | 6 + .../listing-13-13/Cargo.toml | 7 + .../listing-13-13/src/main.rs | 7 + .../listing-13-14/Cargo.lock | 6 + .../listing-13-14/Cargo.toml | 7 + .../listing-13-14/src/main.rs | 11 + .../listing-13-15/Cargo.lock | 6 + .../listing-13-15/Cargo.toml | 7 + .../listing-13-15/src/lib.rs | 18 + .../listing-13-16/Cargo.lock | 6 + .../listing-13-16/Cargo.toml | 7 + .../listing-13-16/src/lib.rs | 17 + .../listing-13-17/Cargo.lock | 6 + .../listing-13-17/Cargo.toml | 7 + .../listing-13-17/output.txt | 13 + .../listing-13-17/src/main.rs | 7 + .../listing-13-18/Cargo.lock | 6 + .../listing-13-18/Cargo.toml | 7 + .../listing-13-18/src/main.rs | 9 + .../listing-13-19/Cargo.lock | 6 + .../listing-13-19/Cargo.toml | 7 + .../listing-13-19/src/lib.rs | 50 + .../listing-13-20/Cargo.lock | 6 + .../listing-13-20/Cargo.toml | 7 + .../listing-13-20/src/lib.rs | 11 + .../listing-13-21/Cargo.lock | 6 + .../listing-13-21/Cargo.toml | 7 + .../listing-13-21/src/lib.rs | 26 + .../listing-13-22/Cargo.lock | 6 + .../listing-13-22/Cargo.toml | 7 + .../listing-13-22/src/lib.rs | 43 + .../listing-13-23/Cargo.lock | 6 + .../listing-13-23/Cargo.toml | 7 + .../listing-13-23/src/lib.rs | 53 + .../listing-13-25/Cargo.lock | 6 + .../listing-13-25/Cargo.toml | 7 + .../listing-13-25/poem.txt | 9 + .../listing-13-25/src/lib.rs | 104 + .../listing-13-25/src/main.rs | 23 + .../listing-13-26/Cargo.lock | 6 + .../listing-13-26/Cargo.toml | 7 + .../listing-13-26/poem.txt | 9 + .../listing-13-26/src/lib.rs | 107 + .../listing-13-26/src/main.rs | 17 + .../listing-13-27/Cargo.lock | 6 + .../listing-13-27/Cargo.toml | 7 + .../listing-13-27/poem.txt | 9 + .../listing-13-27/src/lib.rs | 113 + .../listing-13-27/src/main.rs | 17 + .../listing-13-29/Cargo.lock | 6 + .../listing-13-29/Cargo.toml | 7 + .../listing-13-29/poem.txt | 9 + .../listing-13-29/src/lib.rs | 106 + .../listing-13-29/src/main.rs | 17 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 23 + .../src/lib.rs | 47 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/main.rs | 11 + .../no-listing-03-move-closures/Cargo.lock | 6 + .../no-listing-03-move-closures/Cargo.toml | 7 + .../no-listing-03-move-closures/output.txt | 22 + .../no-listing-03-move-closures/src/main.rs | 11 + .../listing-14-01/Cargo.lock | 6 + .../listing-14-01/Cargo.toml | 7 + .../listing-14-01/src/lib.rs | 13 + .../listing-14-02/Cargo.lock | 6 + .../listing-14-02/Cargo.toml | 7 + .../listing-14-02/src/lib.rs | 21 + .../listing-14-03/Cargo.lock | 6 + .../listing-14-03/Cargo.toml | 7 + .../listing-14-03/src/lib.rs | 36 + .../listing-14-04/Cargo.lock | 6 + .../listing-14-04/Cargo.toml | 7 + .../listing-14-04/src/lib.rs | 29 + .../listing-14-04/src/main.rs | 8 + .../listing-14-05/Cargo.lock | 6 + .../listing-14-05/Cargo.toml | 7 + .../listing-14-05/src/lib.rs | 41 + .../listing-14-06/Cargo.lock | 6 + .../listing-14-06/Cargo.toml | 7 + .../listing-14-06/src/lib.rs | 33 + .../listing-14-06/src/main.rs | 13 + .../listing-14-07/add/Cargo.lock | 13 + .../listing-14-07/add/Cargo.toml | 6 + .../listing-14-07/add/add-one/Cargo.toml | 7 + .../listing-14-07/add/add-one/src/lib.rs | 3 + .../listing-14-07/add/adder/Cargo.toml | 9 + .../listing-14-07/add/adder/src/main.rs | 10 + .../add/Cargo.lock | 6 + .../add/Cargo.toml | 5 + .../add/adder/Cargo.toml | 7 + .../add/adder/src/main.rs | 3 + .../add/Cargo.lock | 13 + .../add/Cargo.toml | 6 + .../add/add-one/Cargo.toml | 7 + .../add/add-one/src/lib.rs | 3 + .../add/adder/Cargo.toml | 9 + .../add/adder/src/main.rs | 3 + .../add/Cargo.lock | 94 + .../add/Cargo.toml | 6 + .../add/add-one/Cargo.toml | 8 + .../add/add-one/src/lib.rs | 5 + .../add/adder/Cargo.toml | 9 + .../add/adder/src/main.rs | 10 + .../add/Cargo.lock | 13 + .../add/Cargo.toml | 6 + .../add/add-one/Cargo.toml | 7 + .../add/add-one/src/lib.rs | 13 + .../add/adder/Cargo.toml | 9 + .../add/adder/src/main.rs | 10 + .../output-only-01-adder-crate/add/Cargo.toml | 5 + .../add/rustfmt-ignore | 2 + .../output-only-02-add-one/add/Cargo.lock | 13 + .../output-only-02-add-one/add/Cargo.toml | 6 + .../add/add-one/Cargo.toml | 9 + .../add/add-one/src/lib.rs | 7 + .../add/adder/Cargo.toml | 9 + .../add/adder/src/main.rs | 3 + .../output-only-03-use-rand/add/Cargo.lock | 94 + .../output-only-03-use-rand/add/Cargo.toml | 6 + .../add/add-one/Cargo.toml | 8 + .../add/add-one/src/lib.rs | 5 + .../add/adder/Cargo.toml | 9 + .../add/adder/src/main.rs | 11 + .../listing-15-01/Cargo.lock | 6 + .../listing-15-01/Cargo.toml | 7 + .../listing-15-01/src/main.rs | 4 + .../listing-15-02/Cargo.lock | 6 + .../listing-15-02/Cargo.toml | 7 + .../listing-15-02/src/main.rs | 8 + .../listing-15-03/Cargo.lock | 6 + .../listing-15-03/Cargo.toml | 7 + .../listing-15-03/output.txt | 28 + .../listing-15-03/src/main.rs | 12 + .../listing-15-05/Cargo.lock | 6 + .../listing-15-05/Cargo.toml | 7 + .../listing-15-05/src/main.rs | 10 + .../listing-15-06/Cargo.lock | 6 + .../listing-15-06/Cargo.toml | 7 + .../listing-15-06/src/main.rs | 7 + .../listing-15-07/Cargo.lock | 6 + .../listing-15-07/Cargo.toml | 7 + .../listing-15-07/src/main.rs | 7 + .../listing-15-08/Cargo.lock | 6 + .../listing-15-08/Cargo.toml | 7 + .../listing-15-08/src/main.rs | 11 + .../listing-15-09/Cargo.lock | 6 + .../listing-15-09/Cargo.toml | 7 + .../listing-15-09/output.txt | 14 + .../listing-15-09/src/main.rs | 17 + .../listing-15-10/Cargo.lock | 6 + .../listing-15-10/Cargo.toml | 7 + .../listing-15-10/src/main.rs | 27 + .../listing-15-11/Cargo.lock | 6 + .../listing-15-11/Cargo.toml | 7 + .../listing-15-11/src/main.rs | 7 + .../listing-15-12/Cargo.lock | 6 + .../listing-15-12/Cargo.toml | 7 + .../listing-15-12/src/main.rs | 28 + .../listing-15-13/Cargo.lock | 6 + .../listing-15-13/Cargo.toml | 7 + .../listing-15-13/src/main.rs | 28 + .../listing-15-14/Cargo.lock | 6 + .../listing-15-14/Cargo.toml | 7 + .../listing-15-14/output.txt | 7 + .../listing-15-14/src/main.rs | 19 + .../listing-15-15/Cargo.lock | 6 + .../listing-15-15/Cargo.toml | 7 + .../listing-15-15/output.txt | 14 + .../listing-15-15/src/main.rs | 20 + .../listing-15-16/Cargo.lock | 6 + .../listing-15-16/Cargo.toml | 7 + .../listing-15-16/output.txt | 7 + .../listing-15-16/src/main.rs | 20 + .../listing-15-17/Cargo.lock | 6 + .../listing-15-17/Cargo.toml | 7 + .../listing-15-17/output.txt | 18 + .../listing-15-17/src/main.rs | 12 + .../listing-15-18/Cargo.lock | 6 + .../listing-15-18/Cargo.toml | 7 + .../listing-15-18/src/main.rs | 13 + .../listing-15-19/Cargo.lock | 6 + .../listing-15-19/Cargo.toml | 7 + .../listing-15-19/output.txt | 8 + .../listing-15-19/src/main.rs | 21 + .../listing-15-20/Cargo.lock | 6 + .../listing-15-20/Cargo.toml | 7 + .../listing-15-20/src/lib.rs | 38 + .../listing-15-21/Cargo.lock | 6 + .../listing-15-21/Cargo.toml | 7 + .../listing-15-21/output.txt | 16 + .../listing-15-21/src/lib.rs | 73 + .../listing-15-22/Cargo.lock | 6 + .../listing-15-22/Cargo.toml | 7 + .../listing-15-22/src/lib.rs | 80 + .../listing-15-23/Cargo.lock | 6 + .../listing-15-23/Cargo.toml | 7 + .../listing-15-23/output.txt | 21 + .../listing-15-23/src/lib.rs | 78 + .../listing-15-24/Cargo.lock | 6 + .../listing-15-24/Cargo.toml | 7 + .../listing-15-24/output.txt | 7 + .../listing-15-24/src/main.rs | 24 + .../listing-15-25/Cargo.lock | 6 + .../listing-15-25/Cargo.toml | 7 + .../listing-15-25/src/main.rs | 20 + .../listing-15-26/Cargo.lock | 6 + .../listing-15-26/Cargo.toml | 7 + .../listing-15-26/output.txt | 11 + .../listing-15-26/src/main.rs | 44 + .../listing-15-27/Cargo.lock | 6 + .../listing-15-27/Cargo.toml | 7 + .../listing-15-27/src/main.rs | 24 + .../listing-15-28/Cargo.lock | 6 + .../listing-15-28/Cargo.toml | 7 + .../listing-15-28/src/main.rs | 33 + .../listing-15-29/Cargo.lock | 6 + .../listing-15-29/Cargo.toml | 7 + .../listing-15-29/src/main.rs | 54 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/main.rs | 4 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 17 + .../src/main.rs | 7 + .../listing-16-01/Cargo.lock | 6 + .../listing-16-01/Cargo.toml | 7 + .../listing-16-01/src/main.rs | 16 + .../listing-16-02/Cargo.lock | 6 + .../listing-16-02/Cargo.toml | 7 + .../listing-16-02/src/main.rs | 18 + .../listing-16-03/Cargo.lock | 6 + .../listing-16-03/Cargo.toml | 7 + .../listing-16-03/output.txt | 29 + .../listing-16-03/src/main.rs | 11 + .../listing-16-04/Cargo.lock | 6 + .../listing-16-04/Cargo.toml | 7 + .../listing-16-04/src/main.rs | 13 + .../listing-16-05/Cargo.lock | 6 + .../listing-16-05/Cargo.toml | 7 + .../listing-16-05/src/main.rs | 11 + .../listing-16-06/Cargo.lock | 6 + .../listing-16-06/Cargo.toml | 7 + .../listing-16-06/src/main.rs | 5 + .../listing-16-07/Cargo.lock | 6 + .../listing-16-07/Cargo.toml | 7 + .../listing-16-07/src/main.rs | 11 + .../listing-16-08/Cargo.lock | 6 + .../listing-16-08/Cargo.toml | 7 + .../listing-16-08/src/main.rs | 14 + .../listing-16-09/Cargo.lock | 6 + .../listing-16-09/Cargo.toml | 7 + .../listing-16-09/output.txt | 18 + .../listing-16-09/src/main.rs | 15 + .../listing-16-10/Cargo.lock | 6 + .../listing-16-10/Cargo.toml | 7 + .../listing-16-10/src/main.rs | 25 + .../listing-16-11/Cargo.lock | 6 + .../listing-16-11/Cargo.toml | 7 + .../listing-16-11/src/main.rs | 46 + .../listing-16-12/Cargo.lock | 6 + .../listing-16-12/Cargo.toml | 7 + .../listing-16-12/src/main.rs | 12 + .../listing-16-13/Cargo.lock | 6 + .../listing-16-13/Cargo.toml | 7 + .../listing-16-13/output.txt | 19 + .../listing-16-13/src/main.rs | 22 + .../listing-16-14/Cargo.lock | 6 + .../listing-16-14/Cargo.toml | 7 + .../listing-16-14/output.txt | 17 + .../listing-16-14/src/main.rs | 24 + .../listing-16-15/Cargo.lock | 6 + .../listing-16-15/Cargo.toml | 7 + .../listing-16-15/src/main.rs | 23 + .../no-listing-01-join-too-early/Cargo.lock | 6 + .../no-listing-01-join-too-early/Cargo.toml | 7 + .../no-listing-01-join-too-early/src/main.rs | 18 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 27 + .../output-only-01-move-drop/Cargo.lock | 6 + .../output-only-01-move-drop/Cargo.toml | 7 + .../output-only-01-move-drop/output.txt | 22 + .../output-only-01-move-drop/src/main.rs | 13 + .../ch17-oop/listing-17-01/Cargo.lock | 6 + .../ch17-oop/listing-17-01/Cargo.toml | 7 + .../ch17-oop/listing-17-01/src/lib.rs | 4 + .../ch17-oop/listing-17-02/Cargo.lock | 6 + .../ch17-oop/listing-17-02/Cargo.toml | 7 + .../ch17-oop/listing-17-02/src/lib.rs | 33 + .../ch17-oop/listing-17-03/Cargo.lock | 6 + .../ch17-oop/listing-17-03/Cargo.toml | 7 + .../ch17-oop/listing-17-03/src/lib.rs | 3 + .../ch17-oop/listing-17-04/Cargo.lock | 6 + .../ch17-oop/listing-17-04/Cargo.toml | 7 + .../ch17-oop/listing-17-04/src/lib.rs | 9 + .../ch17-oop/listing-17-05/Cargo.lock | 6 + .../ch17-oop/listing-17-05/Cargo.toml | 7 + .../ch17-oop/listing-17-05/src/lib.rs | 17 + .../ch17-oop/listing-17-06/Cargo.lock | 6 + .../ch17-oop/listing-17-06/Cargo.toml | 7 + .../ch17-oop/listing-17-06/src/lib.rs | 20 + .../ch17-oop/listing-17-07/Cargo.lock | 6 + .../ch17-oop/listing-17-07/Cargo.toml | 7 + .../ch17-oop/listing-17-07/src/lib.rs | 31 + .../ch17-oop/listing-17-08/Cargo.lock | 6 + .../ch17-oop/listing-17-08/Cargo.toml | 7 + .../ch17-oop/listing-17-08/src/lib.rs | 27 + .../ch17-oop/listing-17-08/src/main.rs | 17 + .../ch17-oop/listing-17-09/Cargo.lock | 6 + .../ch17-oop/listing-17-09/Cargo.toml | 7 + .../ch17-oop/listing-17-09/src/lib.rs | 27 + .../ch17-oop/listing-17-09/src/main.rs | 40 + .../ch17-oop/listing-17-10/Cargo.lock | 6 + .../ch17-oop/listing-17-10/Cargo.toml | 7 + .../ch17-oop/listing-17-10/output.txt | 16 + .../ch17-oop/listing-17-10/src/lib.rs | 27 + .../ch17-oop/listing-17-10/src/main.rs | 9 + .../ch17-oop/listing-17-11/Cargo.lock | 6 + .../ch17-oop/listing-17-11/Cargo.toml | 7 + .../ch17-oop/listing-17-11/src/main.rs | 20 + .../ch17-oop/listing-17-12/Cargo.lock | 6 + .../ch17-oop/listing-17-12/Cargo.toml | 7 + .../ch17-oop/listing-17-12/src/lib.rs | 19 + .../ch17-oop/listing-17-12/src/main.rs | 14 + .../ch17-oop/listing-17-13/Cargo.lock | 6 + .../ch17-oop/listing-17-13/Cargo.toml | 7 + .../ch17-oop/listing-17-13/src/lib.rs | 30 + .../ch17-oop/listing-17-13/src/main.rs | 14 + .../ch17-oop/listing-17-14/Cargo.lock | 6 + .../ch17-oop/listing-17-14/Cargo.toml | 7 + .../ch17-oop/listing-17-14/src/lib.rs | 34 + .../ch17-oop/listing-17-14/src/main.rs | 14 + .../ch17-oop/listing-17-15/Cargo.lock | 6 + .../ch17-oop/listing-17-15/Cargo.toml | 7 + .../ch17-oop/listing-17-15/src/lib.rs | 54 + .../ch17-oop/listing-17-15/src/main.rs | 14 + .../ch17-oop/listing-17-16/Cargo.lock | 6 + .../ch17-oop/listing-17-16/Cargo.toml | 7 + .../ch17-oop/listing-17-16/src/lib.rs | 85 + .../ch17-oop/listing-17-16/src/main.rs | 14 + .../ch17-oop/listing-17-17/Cargo.lock | 6 + .../ch17-oop/listing-17-17/Cargo.toml | 7 + .../ch17-oop/listing-17-17/src/lib.rs | 82 + .../ch17-oop/listing-17-17/src/main.rs | 14 + .../ch17-oop/listing-17-18/Cargo.lock | 6 + .../ch17-oop/listing-17-18/Cargo.toml | 7 + .../ch17-oop/listing-17-18/src/lib.rs | 94 + .../ch17-oop/listing-17-18/src/main.rs | 14 + .../ch17-oop/listing-17-19/Cargo.lock | 6 + .../ch17-oop/listing-17-19/Cargo.toml | 7 + .../ch17-oop/listing-17-19/src/lib.rs | 25 + .../ch17-oop/listing-17-20/Cargo.lock | 6 + .../ch17-oop/listing-17-20/Cargo.toml | 7 + .../ch17-oop/listing-17-20/src/lib.rs | 48 + .../ch17-oop/listing-17-21/Cargo.lock | 6 + .../ch17-oop/listing-17-21/Cargo.toml | 7 + .../ch17-oop/listing-17-21/src/lib.rs | 43 + .../ch17-oop/listing-17-21/src/main.rs | 13 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 16 + .../src/lib.rs | 3 + .../listing-18-01/Cargo.lock | 6 + .../listing-18-01/Cargo.toml | 7 + .../listing-18-01/src/main.rs | 19 + .../listing-18-02/Cargo.lock | 6 + .../listing-18-02/Cargo.toml | 7 + .../listing-18-02/src/main.rs | 13 + .../listing-18-03/Cargo.lock | 6 + .../listing-18-03/Cargo.toml | 7 + .../listing-18-03/output.txt | 7 + .../listing-18-03/src/main.rs | 9 + .../listing-18-04/Cargo.lock | 6 + .../listing-18-04/Cargo.toml | 7 + .../listing-18-04/src/main.rs | 5 + .../listing-18-05/Cargo.lock | 6 + .../listing-18-05/Cargo.toml | 7 + .../listing-18-05/output.txt | 17 + .../listing-18-05/src/main.rs | 5 + .../listing-18-06/Cargo.lock | 6 + .../listing-18-06/Cargo.toml | 7 + .../listing-18-06/src/main.rs | 7 + .../listing-18-07/Cargo.lock | 6 + .../listing-18-07/Cargo.toml | 7 + .../listing-18-07/src/main.rs | 8 + .../listing-18-08/Cargo.lock | 6 + .../listing-18-08/Cargo.toml | 7 + .../listing-18-08/output.txt | 21 + .../listing-18-08/src/main.rs | 6 + .../listing-18-09/Cargo.lock | 6 + .../listing-18-09/Cargo.toml | 7 + .../listing-18-09/src/main.rs | 8 + .../listing-18-10/Cargo.lock | 6 + .../listing-18-10/Cargo.toml | 7 + .../listing-18-10/output.txt | 15 + .../listing-18-10/src/main.rs | 7 + .../listing-18-11/Cargo.lock | 6 + .../listing-18-11/Cargo.toml | 7 + .../listing-18-11/src/main.rs | 14 + .../listing-18-12/Cargo.lock | 6 + .../listing-18-12/Cargo.toml | 7 + .../listing-18-12/src/main.rs | 12 + .../listing-18-13/Cargo.lock | 6 + .../listing-18-13/Cargo.toml | 7 + .../listing-18-13/src/main.rs | 12 + .../listing-18-14/Cargo.lock | 6 + .../listing-18-14/Cargo.toml | 7 + .../listing-18-14/src/main.rs | 16 + .../listing-18-15/Cargo.lock | 6 + .../listing-18-15/Cargo.toml | 7 + .../listing-18-15/src/main.rs | 27 + .../listing-18-16/Cargo.lock | 6 + .../listing-18-16/Cargo.toml | 7 + .../listing-18-16/src/main.rs | 27 + .../listing-18-17/Cargo.lock | 6 + .../listing-18-17/Cargo.toml | 7 + .../listing-18-17/src/main.rs | 7 + .../listing-18-18/Cargo.lock | 6 + .../listing-18-18/Cargo.toml | 7 + .../listing-18-18/src/main.rs | 17 + .../listing-18-19/Cargo.lock | 6 + .../listing-18-19/Cargo.toml | 7 + .../listing-18-19/src/main.rs | 11 + .../listing-18-20/Cargo.lock | 6 + .../listing-18-20/Cargo.toml | 7 + .../listing-18-20/src/main.rs | 4 + .../listing-18-21/Cargo.lock | 6 + .../listing-18-21/Cargo.toml | 7 + .../listing-18-21/src/main.rs | 11 + .../listing-18-22/Cargo.lock | 6 + .../listing-18-22/Cargo.toml | 7 + .../listing-18-22/src/main.rs | 11 + .../listing-18-23/Cargo.lock | 6 + .../listing-18-23/Cargo.toml | 7 + .../listing-18-23/src/main.rs | 15 + .../listing-18-24/Cargo.lock | 6 + .../listing-18-24/Cargo.toml | 7 + .../listing-18-24/src/main.rs | 9 + .../listing-18-25/Cargo.lock | 4 + .../listing-18-25/Cargo.toml | 7 + .../listing-18-25/output.txt | 15 + .../listing-18-25/rustfmt-ignore | 1 + .../listing-18-25/src/main.rs | 9 + .../listing-18-26/Cargo.lock | 6 + .../listing-18-26/Cargo.toml | 7 + .../listing-18-26/src/main.rs | 11 + .../listing-18-27/Cargo.lock | 6 + .../listing-18-27/Cargo.toml | 7 + .../listing-18-27/src/main.rs | 12 + .../listing-18-28/Cargo.lock | 6 + .../listing-18-28/Cargo.toml | 7 + .../listing-18-28/src/main.rs | 11 + .../listing-18-29/Cargo.lock | 6 + .../listing-18-29/Cargo.toml | 7 + .../listing-18-29/src/main.rs | 19 + .../no-listing-01-literals/Cargo.lock | 6 + .../no-listing-01-literals/Cargo.toml | 7 + .../no-listing-01-literals/src/main.rs | 12 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 11 + .../no-listing-03-ranges/Cargo.lock | 6 + .../no-listing-03-ranges/Cargo.toml | 7 + .../no-listing-03-ranges/src/main.rs | 10 + .../no-listing-04-ranges-of-char/Cargo.lock | 6 + .../no-listing-04-ranges-of-char/Cargo.toml | 7 + .../no-listing-04-ranges-of-char/src/main.rs | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 10 + .../listing-13-21-reproduced/Cargo.lock | 6 + .../listing-13-21-reproduced/Cargo.toml | 7 + .../listing-13-21-reproduced/src/lib.rs | 27 + .../listing-19-01/Cargo.lock | 6 + .../listing-19-01/Cargo.toml | 7 + .../listing-19-01/src/main.rs | 8 + .../listing-19-02/Cargo.lock | 6 + .../listing-19-02/Cargo.toml | 7 + .../listing-19-02/src/main.rs | 6 + .../listing-19-03/Cargo.lock | 6 + .../listing-19-03/Cargo.toml | 7 + .../listing-19-03/src/main.rs | 13 + .../listing-19-04/Cargo.lock | 6 + .../listing-19-04/Cargo.toml | 7 + .../listing-19-04/src/main.rs | 12 + .../listing-19-05/Cargo.lock | 6 + .../listing-19-05/Cargo.toml | 7 + .../listing-19-05/output.txt | 21 + .../listing-19-05/src/main.rs | 14 + .../listing-19-06/Cargo.lock | 6 + .../listing-19-06/Cargo.toml | 7 + .../listing-19-06/src/main.rs | 22 + .../listing-19-07/Cargo.lock | 6 + .../listing-19-07/Cargo.toml | 7 + .../listing-19-07/src/main.rs | 10 + .../listing-19-08/Cargo.lock | 6 + .../listing-19-08/Cargo.toml | 7 + .../listing-19-08/src/main.rs | 9 + .../listing-19-09/Cargo.lock | 6 + .../listing-19-09/Cargo.toml | 7 + .../listing-19-09/src/main.rs | 5 + .../listing-19-10/Cargo.lock | 6 + .../listing-19-10/Cargo.toml | 7 + .../listing-19-10/src/main.rs | 15 + .../listing-19-11/Cargo.lock | 6 + .../listing-19-11/Cargo.toml | 7 + .../listing-19-11/src/main.rs | 9 + .../listing-19-12/Cargo.lock | 6 + .../listing-19-12/Cargo.toml | 7 + .../listing-19-12/src/lib.rs | 5 + .../listing-19-13/Cargo.lock | 6 + .../listing-19-13/Cargo.toml | 7 + .../listing-19-13/src/lib.rs | 3 + .../listing-19-14/Cargo.lock | 6 + .../listing-19-14/Cargo.toml | 7 + .../listing-19-14/src/main.rs | 25 + .../listing-19-15/Cargo.lock | 6 + .../listing-19-15/Cargo.toml | 7 + .../listing-19-15/src/lib.rs | 12 + .../listing-19-16/Cargo.lock | 6 + .../listing-19-16/Cargo.toml | 7 + .../listing-19-16/src/main.rs | 31 + .../listing-19-17/Cargo.lock | 6 + .../listing-19-17/Cargo.toml | 7 + .../listing-19-17/src/main.rs | 34 + .../listing-19-18/Cargo.lock | 6 + .../listing-19-18/Cargo.toml | 7 + .../listing-19-18/output.txt | 7 + .../listing-19-18/src/main.rs | 36 + .../listing-19-19/Cargo.lock | 6 + .../listing-19-19/Cargo.toml | 7 + .../listing-19-19/output.txt | 5 + .../listing-19-19/src/main.rs | 21 + .../listing-19-20/Cargo.lock | 6 + .../listing-19-20/Cargo.toml | 7 + .../listing-19-20/output.txt | 19 + .../listing-19-20/src/main.rs | 23 + .../listing-19-21/Cargo.lock | 6 + .../listing-19-21/Cargo.toml | 7 + .../listing-19-21/output.txt | 5 + .../listing-19-21/src/main.rs | 23 + .../listing-19-22/Cargo.lock | 6 + .../listing-19-22/Cargo.toml | 7 + .../listing-19-22/src/main.rs | 17 + .../listing-19-23/Cargo.lock | 6 + .../listing-19-23/Cargo.toml | 7 + .../listing-19-23/src/main.rs | 14 + .../listing-19-24/Cargo.lock | 6 + .../listing-19-24/Cargo.toml | 7 + .../listing-19-24/src/main.rs | 16 + .../listing-19-25/Cargo.lock | 6 + .../listing-19-25/Cargo.toml | 7 + .../listing-19-25/src/main.rs | 18 + .../listing-19-27/Cargo.lock | 6 + .../listing-19-27/Cargo.toml | 7 + .../listing-19-27/src/main.rs | 13 + .../listing-19-28/Cargo.lock | 6 + .../listing-19-28/Cargo.toml | 7 + .../listing-19-28/src/lib.rs | 12 + .../listing-19-30/Cargo.lock | 6 + .../listing-19-30/Cargo.toml | 7 + .../listing-19-30/src/main.rs | 9 + .../listing-19-31/hello_macro/Cargo.lock | 6 + .../listing-19-31/hello_macro/Cargo.toml | 7 + .../hello_macro/hello_macro_derive/Cargo.lock | 46 + .../hello_macro/hello_macro_derive/Cargo.toml | 12 + .../hello_macro/hello_macro_derive/src/lib.rs | 15 + .../listing-19-31/hello_macro/src/lib.rs | 3 + .../listing-19-31/hello_macro/src/main.rs | 13 + .../listing-19-33/hello_macro/Cargo.lock | 6 + .../listing-19-33/hello_macro/Cargo.toml | 7 + .../hello_macro/hello_macro_derive/Cargo.lock | 46 + .../hello_macro/hello_macro_derive/Cargo.toml | 12 + .../hello_macro/hello_macro_derive/src/lib.rs | 29 + .../listing-19-33/hello_macro/src/lib.rs | 3 + .../listing-19-33/hello_macro/src/main.rs | 13 + .../no-listing-01-unsafe-fn/Cargo.lock | 6 + .../no-listing-01-unsafe-fn/Cargo.toml | 7 + .../no-listing-01-unsafe-fn/src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../output.txt | 17 + .../src/main.rs | 27 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 33 + .../no-listing-04-kilometers-alias/Cargo.lock | 6 + .../no-listing-04-kilometers-alias/Cargo.toml | 7 + .../src/main.rs | 12 + .../no-listing-05-write-trait/Cargo.lock | 6 + .../no-listing-05-write-trait/Cargo.toml | 7 + .../no-listing-05-write-trait/src/lib.rs | 10 + .../no-listing-06-result-alias/Cargo.lock | 6 + .../no-listing-06-result-alias/Cargo.toml | 7 + .../no-listing-06-result-alias/src/lib.rs | 17 + .../no-listing-07-never-type/Cargo.lock | 6 + .../no-listing-07-never-type/Cargo.toml | 7 + .../no-listing-07-never-type/src/lib.rs | 10 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 9 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 17 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/main.rs | 9 + .../no-listing-11-cant-create-str/Cargo.lock | 6 + .../no-listing-11-cant-create-str/Cargo.toml | 7 + .../no-listing-11-cant-create-str/src/main.rs | 6 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 3 + .../no-listing-15-map-closure/Cargo.lock | 6 + .../no-listing-15-map-closure/Cargo.toml | 7 + .../no-listing-15-map-closure/src/main.rs | 7 + .../no-listing-16-map-function/Cargo.lock | 6 + .../no-listing-16-map-function/Cargo.toml | 7 + .../no-listing-16-map-function/src/main.rs | 7 + .../no-listing-17-map-initializer/Cargo.lock | 6 + .../no-listing-17-map-initializer/Cargo.toml | 7 + .../no-listing-17-map-initializer/src/main.rs | 10 + .../no-listing-18-returns-closure/Cargo.lock | 6 + .../no-listing-18-returns-closure/Cargo.toml | 7 + .../no-listing-18-returns-closure/output.txt | 30 + .../no-listing-18-returns-closure/src/lib.rs | 3 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../src/lib.rs | 3 + .../hello_macro/Cargo.lock | 6 + .../hello_macro/Cargo.toml | 7 + .../hello_macro/src/lib.rs | 3 + .../pancakes/Cargo.lock | 13 + .../pancakes/Cargo.toml | 8 + .../pancakes/src/main.rs | 13 + .../hello_macro/Cargo.lock | 6 + .../hello_macro/Cargo.toml | 7 + .../hello_macro/hello_macro_derive/Cargo.lock | 46 + .../hello_macro/hello_macro_derive/Cargo.toml | 12 + .../hello_macro/hello_macro_derive/src/lib.rs | 27 + .../hello_macro/src/lib.rs | 3 + .../hello_macro/src/main.rs | 13 + .../pancakes/Cargo.lock | 58 + .../pancakes/Cargo.toml | 9 + .../pancakes/src/main.rs | 9 + .../output-only-01-missing-unsafe/Cargo.lock | 6 + .../output-only-01-missing-unsafe/Cargo.toml | 7 + .../output-only-01-missing-unsafe/output.txt | 16 + .../output-only-01-missing-unsafe/src/main.rs | 7 + .../ch20-web-server/listing-20-01/Cargo.lock | 6 + .../ch20-web-server/listing-20-01/Cargo.toml | 7 + .../ch20-web-server/listing-20-01/src/main.rs | 11 + .../ch20-web-server/listing-20-02/Cargo.lock | 6 + .../ch20-web-server/listing-20-02/Cargo.toml | 7 + .../ch20-web-server/listing-20-02/src/main.rs | 21 + .../ch20-web-server/listing-20-03/Cargo.lock | 6 + .../ch20-web-server/listing-20-03/Cargo.toml | 7 + .../ch20-web-server/listing-20-03/src/main.rs | 26 + .../ch20-web-server/listing-20-04/Cargo.lock | 6 + .../ch20-web-server/listing-20-04/Cargo.toml | 7 + .../ch20-web-server/listing-20-04/hello.html | 11 + .../ch20-web-server/listing-20-04/src/main.rs | 24 + .../ch20-web-server/listing-20-05/Cargo.lock | 6 + .../ch20-web-server/listing-20-05/Cargo.toml | 7 + .../ch20-web-server/listing-20-05/hello.html | 11 + .../ch20-web-server/listing-20-05/src/main.rs | 32 + .../ch20-web-server/listing-20-06/Cargo.lock | 6 + .../ch20-web-server/listing-20-06/Cargo.toml | 7 + .../ch20-web-server/listing-20-06/hello.html | 11 + .../ch20-web-server/listing-20-06/src/main.rs | 36 + .../ch20-web-server/listing-20-07/Cargo.lock | 6 + .../ch20-web-server/listing-20-07/Cargo.toml | 7 + .../ch20-web-server/listing-20-07/hello.html | 11 + .../ch20-web-server/listing-20-07/src/main.rs | 41 + .../ch20-web-server/listing-20-08/404.html | 11 + .../ch20-web-server/listing-20-08/Cargo.lock | 6 + .../ch20-web-server/listing-20-08/Cargo.toml | 7 + .../ch20-web-server/listing-20-08/hello.html | 11 + .../ch20-web-server/listing-20-08/src/main.rs | 38 + .../ch20-web-server/listing-20-09/404.html | 11 + .../ch20-web-server/listing-20-09/Cargo.lock | 6 + .../ch20-web-server/listing-20-09/Cargo.toml | 7 + .../ch20-web-server/listing-20-09/hello.html | 11 + .../ch20-web-server/listing-20-09/src/main.rs | 42 + .../ch20-web-server/listing-20-10/404.html | 11 + .../ch20-web-server/listing-20-10/Cargo.lock | 6 + .../ch20-web-server/listing-20-10/Cargo.toml | 7 + .../ch20-web-server/listing-20-10/hello.html | 11 + .../ch20-web-server/listing-20-10/src/main.rs | 53 + .../ch20-web-server/listing-20-11/404.html | 11 + .../ch20-web-server/listing-20-11/Cargo.lock | 6 + .../ch20-web-server/listing-20-11/Cargo.toml | 7 + .../ch20-web-server/listing-20-11/hello.html | 11 + .../ch20-web-server/listing-20-11/src/main.rs | 44 + .../ch20-web-server/listing-20-12/404.html | 11 + .../ch20-web-server/listing-20-12/Cargo.lock | 6 + .../ch20-web-server/listing-20-12/Cargo.toml | 7 + .../ch20-web-server/listing-20-12/hello.html | 11 + .../ch20-web-server/listing-20-12/output.txt | 14 + .../ch20-web-server/listing-20-12/src/main.rs | 45 + .../ch20-web-server/listing-20-13/404.html | 11 + .../ch20-web-server/listing-20-13/Cargo.lock | 6 + .../ch20-web-server/listing-20-13/Cargo.toml | 7 + .../ch20-web-server/listing-20-13/hello.html | 11 + .../listing-20-13/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-13/src/lib.rs | 30 + .../ch20-web-server/listing-20-14/404.html | 11 + .../ch20-web-server/listing-20-14/Cargo.lock | 6 + .../ch20-web-server/listing-20-14/Cargo.toml | 7 + .../ch20-web-server/listing-20-14/hello.html | 11 + .../listing-20-14/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-14/src/lib.rs | 41 + .../ch20-web-server/listing-20-15/404.html | 11 + .../ch20-web-server/listing-20-15/Cargo.lock | 6 + .../ch20-web-server/listing-20-15/Cargo.toml | 7 + .../ch20-web-server/listing-20-15/hello.html | 11 + .../listing-20-15/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-15/src/lib.rs | 55 + .../ch20-web-server/listing-20-16/404.html | 11 + .../ch20-web-server/listing-20-16/Cargo.lock | 6 + .../ch20-web-server/listing-20-16/Cargo.toml | 7 + .../ch20-web-server/listing-20-16/hello.html | 11 + .../listing-20-16/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-16/src/lib.rs | 62 + .../ch20-web-server/listing-20-17/404.html | 11 + .../ch20-web-server/listing-20-17/Cargo.lock | 6 + .../ch20-web-server/listing-20-17/Cargo.toml | 7 + .../ch20-web-server/listing-20-17/hello.html | 11 + .../ch20-web-server/listing-20-17/output.txt | 17 + .../listing-20-17/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-17/src/lib.rs | 66 + .../ch20-web-server/listing-20-18/404.html | 11 + .../ch20-web-server/listing-20-18/Cargo.lock | 6 + .../ch20-web-server/listing-20-18/Cargo.toml | 7 + .../ch20-web-server/listing-20-18/hello.html | 11 + .../listing-20-18/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-18/src/lib.rs | 78 + .../ch20-web-server/listing-20-19/404.html | 11 + .../ch20-web-server/listing-20-19/Cargo.lock | 6 + .../ch20-web-server/listing-20-19/Cargo.toml | 7 + .../ch20-web-server/listing-20-19/hello.html | 11 + .../listing-20-19/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-19/src/lib.rs | 71 + .../ch20-web-server/listing-20-20/404.html | 11 + .../ch20-web-server/listing-20-20/Cargo.lock | 6 + .../ch20-web-server/listing-20-20/Cargo.toml | 7 + .../ch20-web-server/listing-20-20/hello.html | 11 + .../listing-20-20/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-20/src/lib.rs | 68 + .../ch20-web-server/listing-20-21/404.html | 11 + .../ch20-web-server/listing-20-21/Cargo.lock | 6 + .../ch20-web-server/listing-20-21/Cargo.toml | 7 + .../ch20-web-server/listing-20-21/hello.html | 11 + .../listing-20-21/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-21/src/lib.rs | 67 + .../ch20-web-server/listing-20-22/404.html | 11 + .../ch20-web-server/listing-20-22/Cargo.lock | 6 + .../ch20-web-server/listing-20-22/Cargo.toml | 7 + .../ch20-web-server/listing-20-22/hello.html | 11 + .../ch20-web-server/listing-20-22/output.txt | 14 + .../listing-20-22/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-22/src/lib.rs | 76 + .../ch20-web-server/listing-20-23/404.html | 11 + .../ch20-web-server/listing-20-23/Cargo.lock | 6 + .../ch20-web-server/listing-20-23/Cargo.toml | 7 + .../ch20-web-server/listing-20-23/hello.html | 11 + .../listing-20-23/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-23/src/lib.rs | 107 + .../ch20-web-server/listing-20-24/404.html | 11 + .../ch20-web-server/listing-20-24/Cargo.lock | 6 + .../ch20-web-server/listing-20-24/Cargo.toml | 7 + .../ch20-web-server/listing-20-24/hello.html | 11 + .../listing-20-24/src/bin/main.rs | 44 + .../ch20-web-server/listing-20-24/src/lib.rs | 103 + .../ch20-web-server/listing-20-25/404.html | 11 + .../ch20-web-server/listing-20-25/Cargo.lock | 6 + .../ch20-web-server/listing-20-25/Cargo.toml | 7 + .../ch20-web-server/listing-20-25/hello.html | 11 + .../listing-20-25/src/bin/main.rs | 50 + .../ch20-web-server/listing-20-25/src/lib.rs | 105 + .../404.html | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../hello.html | 11 + .../output.txt | 14 + .../src/bin/main.rs | 46 + .../src/lib.rs | 1 + .../404.html | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../hello.html | 11 + .../output.txt | 14 + .../src/bin/main.rs | 44 + .../src/lib.rs | 11 + .../no-listing-03-define-execute/404.html | 11 + .../no-listing-03-define-execute/Cargo.lock | 6 + .../no-listing-03-define-execute/Cargo.toml | 7 + .../no-listing-03-define-execute/hello.html | 11 + .../no-listing-03-define-execute/output.txt | 3 + .../src/bin/main.rs | 44 + .../no-listing-03-define-execute/src/lib.rs | 20 + .../404.html | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../hello.html | 11 + .../output.txt | 27 + .../src/bin/main.rs | 44 + .../src/lib.rs | 76 + .../no-listing-05-fix-worker-new/404.html | 11 + .../no-listing-05-fix-worker-new/Cargo.lock | 6 + .../no-listing-05-fix-worker-new/Cargo.toml | 7 + .../no-listing-05-fix-worker-new/hello.html | 11 + .../src/bin/main.rs | 44 + .../no-listing-05-fix-worker-new/src/lib.rs | 83 + .../404.html | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../hello.html | 11 + .../src/bin/main.rs | 44 + .../src/lib.rs | 81 + .../404.html | 11 + .../Cargo.lock | 6 + .../Cargo.toml | 7 + .../hello.html | 11 + .../src/bin/main.rs | 44 + .../src/lib.rs | 88 + src/doc/book/rust-toolchain | 2 +- src/doc/book/rustfmt.toml | 1 + .../src/ch18-02-refutability.md | 2 +- src/doc/book/src/appendix-01-keywords.md | 2 +- src/doc/book/src/appendix-02-operators.md | 2 +- src/doc/book/src/appendix-06-translation.md | 4 +- src/doc/book/src/appendix-07-nightly-rust.md | 2 +- src/doc/book/src/ch01-03-hello-cargo.md | 7 +- .../src/ch02-00-guessing-game-tutorial.md | 303 +- .../ch03-00-common-programming-concepts.md | 4 +- .../src/ch03-01-variables-and-mutability.md | 61 +- src/doc/book/src/ch03-02-data-types.md | 94 +- .../book/src/ch03-03-how-functions-work.md | 118 +- src/doc/book/src/ch03-04-comments.md | 15 +- src/doc/book/src/ch03-05-control-flow.md | 197 +- src/doc/book/src/ch04-01-what-is-ownership.md | 138 +- .../src/ch04-02-references-and-borrowing.md | 143 +- src/doc/book/src/ch04-03-slices.md | 114 +- src/doc/book/src/ch05-01-defining-structs.md | 138 +- src/doc/book/src/ch05-02-example-structs.md | 89 +- src/doc/book/src/ch05-03-method-syntax.md | 77 +- src/doc/book/src/ch06-01-defining-an-enum.md | 117 +- src/doc/book/src/ch06-02-match.md | 112 +- src/doc/book/src/ch06-03-if-let.md | 50 +- .../book/src/ch07-01-packages-and-crates.md | 2 +- ...ng-modules-to-control-scope-and-privacy.md | 18 +- ...referring-to-an-item-in-the-module-tree.md | 123 +- ...g-paths-into-scope-with-the-use-keyword.md | 117 +- ...separating-modules-into-different-files.md | 20 +- src/doc/book/src/ch08-01-vectors.md | 85 +- src/doc/book/src/ch08-02-strings.md | 67 +- src/doc/book/src/ch08-03-hash-maps.md | 99 +- ...ch09-01-unrecoverable-errors-with-panic.md | 142 +- .../ch09-02-recoverable-errors-with-result.md | 171 +- .../src/ch09-03-to-panic-or-not-to-panic.md | 46 +- src/doc/book/src/ch10-00-generics.md | 67 +- src/doc/book/src/ch10-01-syntax.md | 163 +- src/doc/book/src/ch10-02-traits.md | 194 +- src/doc/book/src/ch10-03-lifetime-syntax.md | 199 +- src/doc/book/src/ch11-01-writing-tests.md | 377 +- src/doc/book/src/ch11-02-running-tests.md | 149 +- src/doc/book/src/ch11-03-test-organization.md | 105 +- ...h12-01-accepting-command-line-arguments.md | 36 +- src/doc/book/src/ch12-02-reading-a-file.md | 46 +- ...improving-error-handling-and-modularity.md | 205 +- ...2-04-testing-the-librarys-functionality.md | 125 +- ...2-05-working-with-environment-variables.md | 137 +- ...-06-writing-to-stderr-instead-of-stdout.md | 19 +- src/doc/book/src/ch13-01-closures.md | 315 +- src/doc/book/src/ch13-02-iterators.md | 186 +- .../src/ch13-03-improving-our-io-project.md | 87 +- src/doc/book/src/ch14-01-release-profiles.md | 11 +- .../src/ch14-02-publishing-to-crates-io.md | 124 +- src/doc/book/src/ch14-03-cargo-workspaces.md | 122 +- .../book/src/ch14-04-installing-binaries.md | 25 +- src/doc/book/src/ch15-01-box.md | 55 +- src/doc/book/src/ch15-02-deref.md | 140 +- src/doc/book/src/ch15-03-drop.md | 54 +- src/doc/book/src/ch15-04-rc.md | 65 +- .../book/src/ch15-05-interior-mutability.md | 199 +- src/doc/book/src/ch15-06-reference-cycles.md | 206 +- src/doc/book/src/ch16-01-threads.md | 139 +- src/doc/book/src/ch16-02-message-passing.md | 143 +- src/doc/book/src/ch16-03-shared-state.md | 115 +- ...04-extensible-concurrency-sync-and-send.md | 7 +- src/doc/book/src/ch17-01-what-is-oo.md | 36 +- src/doc/book/src/ch17-02-trait-objects.md | 134 +- .../book/src/ch17-03-oo-design-patterns.md | 267 +- .../ch18-01-all-the-places-for-patterns.md | 66 +- src/doc/book/src/ch18-02-refutability.md | 29 +- src/doc/book/src/ch18-03-pattern-syntax.md | 298 +- src/doc/book/src/ch19-01-unsafe-rust.md | 148 +- src/doc/book/src/ch19-03-advanced-traits.md | 274 +- src/doc/book/src/ch19-04-advanced-types.md | 108 +- ...ch19-05-advanced-functions-and-closures.md | 58 +- src/doc/book/src/ch19-06-macros.md | 107 +- src/doc/book/src/ch20-01-single-threaded.md | 167 +- src/doc/book/src/ch20-02-multithreaded.md | 536 +- .../ch20-03-graceful-shutdown-and-cleanup.md | 332 +- src/doc/book/src/title-page.md | 2 +- src/doc/book/tools/nostarch.sh | 15 +- src/doc/book/tools/src/bin/concat_chapters.rs | 35 +- src/doc/book/tools/src/bin/convert_quotes.rs | 50 +- src/doc/book/tools/src/bin/lfp.rs | 93 +- src/doc/book/tools/src/bin/link2print.rs | 62 +- .../book/tools/src/bin/release_listings.rs | 159 + .../book/tools/src/bin/remove_hidden_lines.rs | 83 + src/doc/book/tools/src/bin/remove_links.rs | 18 +- src/doc/book/tools/src/bin/remove_markup.rs | 40 +- src/doc/book/tools/update-rustc.sh | 76 + .../cargo-check-for-faster-checking.md | 2 +- src/doc/embedded-book/ci/install.sh | 4 +- src/doc/embedded-book/ci/script.sh | 6 +- src/doc/embedded-book/src/SUMMARY.md | 4 + .../embedded-book/src/appendix/glossary.md | 16 + .../src/interoperability/c-with-rust.md | 2 +- src/doc/embedded-book/src/intro/index.md | 20 + .../src/static-guarantees/design-contracts.md | 2 +- .../typestate-programming.md | 50 +- src/doc/nomicon/book.toml | 7 + src/doc/nomicon/src/destructors.md | 6 +- src/doc/nomicon/src/ffi.md | 4 +- src/doc/nomicon/src/lifetimes.md | 2 + src/doc/nomicon/src/safe-unsafe-meaning.md | 2 +- src/doc/nomicon/src/subtyping.md | 8 +- src/doc/nomicon/src/vec-alloc.md | 2 +- src/doc/nomicon/src/vec-final.md | 4 +- src/doc/reference/src/attributes.md | 2 +- .../src/behavior-considered-undefined.md | 2 +- src/doc/reference/src/const_eval.md | 6 +- .../reference/src/expressions/array-expr.md | 2 +- .../reference/src/expressions/block-expr.md | 2 +- .../reference/src/items/associated-items.md | 28 +- src/doc/reference/src/items/enumerations.md | 2 +- src/doc/reference/src/items/traits.md | 96 + .../reference/src/items/use-declarations.md | 2 +- src/doc/reference/src/macro-ambiguity.md | 2 +- src/doc/reference/src/paths.md | 3 +- src/doc/reference/src/tokens.md | 2 +- src/doc/reference/src/type-layout.md | 28 +- src/doc/reference/src/types/pointer.md | 6 +- src/doc/reference/src/types/trait-object.md | 2 +- src/doc/robots.txt | 1 - .../src/conversion/from_into.md | 4 +- .../reenter_question_mark.md | 4 +- .../rust-by-example/src/flow_control/for.md | 15 +- .../src/flow_control/if_let.md | 6 +- src/doc/rust-by-example/src/mod/visibility.md | 2 +- .../.editorconfig | 0 .../.travis.yml | 4 +- src/doc/rustc-dev-guide/CNAME | 1 + .../CODE_OF_CONDUCT.md | 0 .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 src/doc/rustc-dev-guide/README.md | 85 + src/doc/rustc-dev-guide/book.toml | 20 + .../ci/check_line_lengths.sh | 0 .../src/SUMMARY.md | 4 + .../src/about-this-guide.md | 2 +- .../src/appendix/background.md | 0 .../src/appendix/bibliography.md | 0 .../src/appendix/code-index.md | 10 +- .../src/appendix/compiler-lecture.md | 27 + .../rustc-dev-guide/src/appendix/glossary.md | 88 + .../src/appendix/humorust.md | 1 + .../src/appendix/stupid-stats.md | 4 +- .../src/borrow_check.md | 0 .../borrow_check/moves_and_initialization.md | 0 .../moves_and_initialization/move_paths.md | 0 .../src/borrow_check/region_inference.md | 3 +- .../region_inference/closure_constraints.md | 0 .../constraint_propagation.md | 4 +- .../region_inference/error_reporting.md | 0 .../region_inference/lifetime_parameters.md | 0 .../region_inference/member_constraints.md | 0 .../placeholders_and_universes.md | 0 .../src/borrow_check/two_phase_borrows.md | 0 .../src/borrow_check/type_check.md | 0 .../src/bug-fix-procedure.md | 2 +- .../src/building/bootstrapping.md | 0 .../build-install-distribution-artifacts.md | 0 .../src/building/compiler-documenting.md | 0 .../src/building/ctags.md | 0 .../src/building/how-to-build-and-run.md | 0 .../src/building/suggested.md | 0 .../src/closure.md | 0 .../src/codegen.md | 0 .../src/codegen/backend-agnostic.md | 4 +- .../src/codegen/debugging.md | 2 + .../src/codegen/updating-llvm.md | 0 .../src/compiler-debugging.md | 0 .../src/compiler-team.md | 0 .../src/compiletest.md | 0 .../src/const-eval.md | 0 .../src/conventions.md | 2 +- .../src/crates-io.md | 0 .../src/debugging-support-in-rustc.md | 6 +- .../src/diagnostics.md | 10 +- .../src/diagnostics/diagnostic-codes.md | 2 +- .../src/diagnostics/lintstore.md | 0 .../src/generic_arguments.md | 0 src/doc/rustc-dev-guide/src/generics.md | 144 + .../src/high-level-overview.md | 6 +- .../src/hir-debugging.md | 0 .../src/hir.md | 2 +- .../src/ice-breaker/about.md | 2 + .../src/ice-breaker/cleanup-crew.md | 114 + .../src/ice-breaker/llvm.md | 2 +- .../src/img/rustc_stages.svg | 0 .../src/implementing_new_features.md | 8 +- .../src/incrcomp-debugging.md | 0 .../src/lowering.md | 0 .../src/macro-expansion.md | 45 +- src/doc/rustc-dev-guide/src/memory.md | 88 + .../src/method-lookup.md | 0 .../src/mir/construction.md | 0 .../src/mir/debugging.md | 0 .../src/mir/index.md | 32 +- .../src/mir/mir_detailed.dot | 0 .../src/mir/mir_detailed.svg | 0 .../src/mir/mir_overview.dot | 0 .../src/mir/mir_overview.svg | 0 .../src/mir/optimizations.md | 10 +- .../src/mir/passes.md | 0 .../src/mir/visitor.md | 0 .../src/miri.md | 0 .../src/name-resolution.md | 27 +- .../src/opaque-types-type-alias-impl-trait.md | 0 .../src/panic-implementation.md | 0 .../src/param_env.md | 0 .../src/part-1-intro.md | 2 +- .../src/part-2-intro.md | 2 +- .../src/profile-guided-optimization.md | 0 .../src/profiling.md | 0 .../src/profiling/with_perf.md | 0 .../src/queries/example-0.counts.txt | 0 .../src/queries/example-0.html | 0 .../src/queries/example-0.png | Bin .../incremental-compilation-in-detail.md | 0 .../src/queries/incremental-compilation.md | 0 .../src/queries/profiling.md | 0 .../query-evaluation-model-in-detail.md | 2 +- .../src/query.md | 52 +- .../src/rustc-driver.md | 13 - .../src/rustdoc.md | 0 .../src/salsa.md | 0 src/doc/rustc-dev-guide/src/sanitizers.md | 74 + .../src/stability.md | 0 .../src/stabilization_guide.md | 0 .../src/test-implementation.md | 14 +- .../src/tests/adding.md | 19 +- .../src/tests/intro.md | 15 +- .../src/tests/running.md | 20 +- .../src/the-parser.md | 12 +- .../src/traits/associated-types.md | 0 .../src/traits/bibliography.md | 0 .../src/traits/caching.md | 0 .../src/traits/canonical-queries.md | 0 .../src/traits/canonicalization.md | 0 .../src/traits/chalk-overview.md | 2 +- .../src/traits/goals-and-clauses.md | 0 .../src/traits/hrtb.md | 2 +- .../src/traits/implied-bounds.md | 0 .../src/traits/index.md | 0 .../src/traits/lowering-module.md | 56 + .../src/traits/lowering-rules.md | 0 .../src/traits/lowering-to-logic.md | 0 .../src/traits/regions.md | 0 .../src/traits/resolution.md | 0 .../src/traits/slg.md | 0 .../src/traits/specialization.md | 0 .../src/traits/wf.md | 0 src/doc/rustc-dev-guide/src/ty-fold.md | 105 + src/doc/rustc-dev-guide/src/ty.md | 331 + .../src/type-checking.md | 0 .../src/type-inference.md | 9 +- .../src/variance.md | 0 .../src/walkthrough.md | 0 .../triagebot.toml | 0 src/doc/rustc-guide/README.md | 85 - src/doc/rustc-guide/book.toml | 20 - src/doc/rustc-guide/ci/install.sh | 24 - .../src/appendix/compiler-lecture.md | 51 - src/doc/rustc-guide/src/appendix/glossary.md | 87 - src/doc/rustc-guide/src/sanitizers.md | 68 - .../rustc-guide/src/traits/lowering-module.md | 65 - src/doc/rustc-guide/src/ty.md | 636 - src/doc/rustc-ux-guidelines.md | 2 +- src/doc/rustc/src/command-line-arguments.md | 9 + src/doc/rustc/src/lints/levels.md | 12 + src/doc/rustdoc/book.toml | 4 + src/doc/rustdoc/src/the-doc-attribute.md | 2 +- src/doc/rustdoc/src/unstable-features.md | 23 +- .../src/compiler-flags/control-flow-guard.md | 34 + .../src/compiler-flags/sanitizer.md | 86 +- .../src/compiler-flags/self-profile-events.md | 74 + .../src/compiler-flags/self-profile.md | 47 + .../src/language-features/const-eval-limit.md | 7 + .../const-in-array-repeat-expressions.md | 2 +- .../src/language-features/doc-spotlight.md | 30 - .../src/language-features/generators.md | 26 +- .../impl-trait-in-bindings.md | 4 +- .../src/language-features/link-cfg.md | 5 + .../language-features/marker-trait-attr.md | 2 +- .../src/language-features/no-sanitize.md | 29 + .../src/language-features/plugin.md | 6 +- .../src/language-features/trait-alias.md | 2 +- .../language-features/transparent-unions.md | 2 +- .../src/library-features/allocator-api.md | 2 +- .../src/library-features/read-initializer.md | 7 - .../tidy-test-never-used-anywhere-else.md | 5 + src/etc/debugger_pretty_printers_common.py | 6 +- src/etc/dec2flt_table.py | 2 +- src/etc/gdb_rust_pretty_printing.py | 43 +- src/etc/generate-deriving-span-tests.py | 15 +- src/etc/generate-keyword-tests.py | 1 - src/etc/htmldocck.py | 40 +- src/etc/installer/gfx/rust-logo.png | Bin 5844 -> 3909 bytes src/etc/lldb_batchmode.py | 1 + src/etc/lldb_rust_formatters.py | 48 +- src/liballoc/alloc.rs | 76 +- src/liballoc/alloc/tests.rs | 2 +- src/liballoc/benches/btree/map.rs | 56 + src/liballoc/benches/btree/set.rs | 101 +- src/liballoc/boxed.rs | 64 +- src/liballoc/collections/binary_heap.rs | 20 +- src/liballoc/collections/btree/map.rs | 484 +- src/liballoc/collections/btree/mod.rs | 12 + src/liballoc/collections/btree/navigate.rs | 243 + src/liballoc/collections/btree/node.rs | 334 +- src/liballoc/collections/btree/search.rs | 16 +- src/liballoc/collections/btree/set.rs | 13 +- src/liballoc/collections/linked_list.rs | 73 +- src/liballoc/collections/vec_deque.rs | 131 +- src/liballoc/collections/vec_deque/drain.rs | 126 + src/liballoc/fmt.rs | 15 + src/liballoc/lib.rs | 1 + src/liballoc/raw_vec.rs | 74 +- src/liballoc/raw_vec/tests.rs | 4 +- src/liballoc/rc.rs | 6 +- src/liballoc/string.rs | 27 +- src/liballoc/sync.rs | 6 +- src/liballoc/tests/binary_heap.rs | 33 + src/liballoc/tests/btree/map.rs | 121 +- src/liballoc/tests/btree/set.rs | 27 +- src/liballoc/tests/heap.rs | 6 +- src/liballoc/tests/lib.rs | 1 + src/liballoc/tests/linked_list.rs | 70 +- src/liballoc/tests/slice.rs | 84 +- src/liballoc/tests/str.rs | 43 + src/liballoc/tests/string.rs | 4 + src/liballoc/tests/vec.rs | 64 + src/liballoc/tests/vec_deque.rs | 74 +- src/liballoc/vec.rs | 70 +- src/libcore/alloc.rs | 552 +- src/libcore/any.rs | 8 +- src/libcore/cell.rs | 64 + src/libcore/char/methods.rs | 80 +- src/libcore/cmp.rs | 64 +- src/libcore/convert/mod.rs | 2 +- src/libcore/fmt/float.rs | 2 - src/libcore/fmt/mod.rs | 68 +- src/libcore/fmt/num.rs | 163 + src/libcore/fmt/rt/v1.rs | 9 - src/libcore/future/future.rs | 1 - src/libcore/hash/sip.rs | 6 +- src/libcore/intrinsics.rs | 511 +- src/libcore/iter/adapters/mod.rs | 113 +- src/libcore/iter/mod.rs | 7 +- src/libcore/iter/range.rs | 38 +- src/libcore/iter/sources.rs | 20 +- src/libcore/iter/traits/exact_size.rs | 4 +- src/libcore/iter/traits/iterator.rs | 107 +- src/libcore/lib.rs | 20 +- src/libcore/marker.rs | 4 + src/libcore/mem/manually_drop.rs | 2 +- src/libcore/mem/maybe_uninit.rs | 2 +- src/libcore/mem/mod.rs | 5 +- src/libcore/num/dec2flt/rawfp.rs | 10 +- src/libcore/num/f32.rs | 118 +- src/libcore/num/f64.rs | 111 +- src/libcore/num/flt2dec/mod.rs | 32 +- src/libcore/num/i128.rs | 3 + src/libcore/num/i16.rs | 3 + src/libcore/num/i32.rs | 3 + src/libcore/num/i64.rs | 3 + src/libcore/num/i8.rs | 3 + src/libcore/num/int_macros.rs | 26 +- src/libcore/num/isize.rs | 3 + src/libcore/num/mod.rs | 522 +- src/libcore/num/u128.rs | 5 +- src/libcore/num/u16.rs | 5 +- src/libcore/num/u32.rs | 5 +- src/libcore/num/u64.rs | 5 +- src/libcore/num/u8.rs | 5 +- src/libcore/num/uint_macros.rs | 13 - src/libcore/num/usize.rs | 5 +- src/libcore/ops/generator.rs | 35 +- src/libcore/ops/range.rs | 53 +- src/libcore/option.rs | 36 +- src/libcore/pin.rs | 4 +- src/libcore/primitive.rs | 67 + src/libcore/ptr/const_ptr.rs | 8 +- src/libcore/ptr/mod.rs | 73 +- src/libcore/ptr/mut_ptr.rs | 10 +- src/libcore/result.rs | 118 +- src/libcore/slice/mod.rs | 386 +- src/libcore/str/mod.rs | 177 +- src/libcore/str/pattern.rs | 2 +- src/libcore/sync/atomic.rs | 4 +- src/libcore/tests/alloc.rs | 3 + src/libcore/tests/fmt/num.rs | 80 + src/libcore/tests/hash/sip.rs | 38 +- src/libcore/tests/iter.rs | 18 + src/libcore/tests/lib.rs | 4 +- src/libcore/tests/num/flt2dec/mod.rs | 460 +- src/libcore/tests/slice.rs | 12 + src/libcore/tests/time.rs | 6 + src/libfmt_macros/lib.rs | 2 +- src/libgraphviz/lib.rs | 10 + src/libpanic_unwind/seh.rs | 17 +- src/libproc_macro/bridge/client.rs | 4 +- src/libproc_macro/diagnostic.rs | 17 +- src/librustc/Cargo.toml | 8 +- src/librustc/arena.rs | 17 +- src/librustc/benches/lib.rs | 1 - src/librustc/dep_graph/dep_node.rs | 204 +- src/librustc/dep_graph/graph.rs | 44 +- src/librustc/dep_graph/mod.rs | 3 +- src/librustc/dep_graph/safe.rs | 2 +- src/librustc/hir/check_attr.rs | 587 - src/librustc/hir/exports.rs | 2 +- src/librustc/hir/map/blocks.rs | 2 +- src/librustc/hir/map/collector.rs | 12 +- src/librustc/hir/map/definitions.rs | 6 +- src/librustc/hir/map/hir_id_validator.rs | 2 +- src/librustc/hir/map/mod.rs | 141 +- src/librustc/hir/mod.rs | 54 +- src/librustc/ich/hcx.rs | 37 +- src/librustc/ich/impls_hir.rs | 43 +- src/librustc/ich/impls_syntax.rs | 15 +- src/librustc/ich/impls_ty.rs | 5 +- src/librustc/infer/canonical.rs | 357 + src/librustc/infer/canonical/mod.rs | 493 - src/librustc/infer/error_reporting/mod.rs | 2070 ---- .../error_reporting/nice_region_error/mod.rs | 91 - .../error_reporting/nice_region_error/util.rs | 132 - src/librustc/infer/higher_ranked/mod.rs | 138 - .../infer/lexical_region_resolve/mod.rs | 940 -- src/librustc/infer/mod.rs | 1756 +-- src/librustc/infer/nll_relate/mod.rs | 996 -- src/librustc/infer/opaque_types/mod.rs | 1289 -- src/librustc/infer/region_constraints/mod.rs | 938 -- src/librustc/infer/unify_key.rs | 18 +- src/librustc/lib.rs | 15 +- src/librustc/lint.rs | 244 +- src/librustc/macros.rs | 37 - src/librustc/middle/codegen_fn_attrs.rs | 13 +- src/librustc/middle/cstore.rs | 9 +- src/librustc/middle/free_region.rs | 60 +- src/librustc/middle/lang_items.rs | 425 +- src/librustc/middle/limits.rs | 66 + src/librustc/middle/mod.rs | 3 +- src/librustc/middle/recursion_limit.rs | 33 - src/librustc/middle/region.rs | 2 +- src/librustc/middle/stability.rs | 42 +- src/librustc/middle/weak_lang_items.rs | 167 - src/librustc/mir/interpret/allocation.rs | 22 +- src/librustc/mir/interpret/error.rs | 217 +- src/librustc/mir/interpret/mod.rs | 22 +- src/librustc/mir/interpret/pointer.rs | 4 +- src/librustc/mir/interpret/queries.rs | 36 +- src/librustc/mir/interpret/value.rs | 90 +- src/librustc/mir/mod.rs | 141 +- src/librustc/mir/mono.rs | 6 +- src/librustc/mir/query.rs | 8 +- src/librustc/mir/tcx.rs | 8 +- src/librustc/mir/traversal.rs | 4 +- src/librustc/mir/visit.rs | 20 +- src/librustc/query/mod.rs | 143 +- src/librustc/traits/chalk_fulfill.rs | 159 - src/librustc/traits/codegen/mod.rs | 110 - src/librustc/traits/error_reporting/mod.rs | 1427 --- .../error_reporting/on_unimplemented.rs | 213 - src/librustc/traits/misc.rs | 202 - src/librustc/traits/mod.rs | 984 +- src/librustc/traits/object_safety.rs | 730 -- src/librustc/traits/on_unimplemented.rs | 385 - src/librustc/traits/query.rs | 332 + src/librustc/traits/query/dropck_outlives.rs | 206 - src/librustc/traits/query/method_autoderef.rs | 33 - src/librustc/traits/query/mod.rs | 50 - src/librustc/traits/query/normalize.rs | 190 - src/librustc/traits/query/outlives_bounds.rs | 139 - .../traits/query/type_op/ascribe_user_type.rs | 36 - src/librustc/traits/query/type_op/eq.rs | 33 - src/librustc/traits/query/type_op/mod.rs | 134 - .../traits/query/type_op/normalize.rs | 80 - src/librustc/traits/query/type_op/subtype.rs | 30 - src/librustc/traits/select.rs | 3887 +----- src/librustc/traits/specialization_graph.rs | 202 + src/librustc/traits/specialize/mod.rs | 462 - .../traits/specialize/specialization_graph.rs | 527 - src/librustc/traits/structural_impls.rs | 148 +- src/librustc/traits/util.rs | 672 -- src/librustc/ty/adjustment.rs | 1 + src/librustc/ty/cast.rs | 2 +- src/librustc/ty/codec.rs | 1 + src/librustc/ty/context.rs | 145 +- src/librustc/ty/error.rs | 19 +- src/librustc/ty/fast_reject.rs | 2 +- src/librustc/ty/flags.rs | 23 +- src/librustc/ty/fold.rs | 22 +- src/librustc/ty/free_region_map.rs | 89 +- src/librustc/ty/instance.rs | 177 +- src/librustc/ty/layout.rs | 76 +- src/librustc/ty/mod.rs | 367 +- src/librustc/ty/normalize_erasing_regions.rs | 5 +- src/librustc/ty/print/mod.rs | 2 +- src/librustc/ty/print/pretty.rs | 35 +- src/librustc/ty/query/caches.rs | 112 + src/librustc/ty/query/config.rs | 22 +- src/librustc/ty/query/job.rs | 309 +- src/librustc/ty/query/keys.rs | 51 +- src/librustc/ty/query/mod.rs | 141 +- src/librustc/ty/query/on_disk_cache.rs | 66 +- src/librustc/ty/query/plumbing.rs | 714 +- src/librustc/ty/query/profiling_support.rs | 43 +- src/librustc/ty/query/stats.rs | 139 + src/librustc/ty/query/values.rs | 7 - src/librustc/ty/relate.rs | 6 +- src/librustc/ty/structural_impls.rs | 25 +- src/librustc/ty/sty.rs | 185 +- src/librustc/ty/util.rs | 146 +- src/librustc_ast/Cargo.toml | 21 + src/librustc_ast/README.md | 9 + src/{libsyntax => librustc_ast}/ast.rs | 336 +- src/{libsyntax => librustc_ast}/ast/tests.rs | 0 src/librustc_ast/attr/mod.rs | 729 ++ src/{libsyntax => librustc_ast}/build.rs | 0 src/{libsyntax => librustc_ast}/entry.rs | 0 .../expand/allocator.rs | 0 src/{libsyntax => librustc_ast}/expand/mod.rs | 0 src/librustc_ast/lib.rs | 63 + src/{libsyntax => librustc_ast}/mut_visit.rs | 106 +- src/librustc_ast/node_id.rs | 48 + src/{libsyntax => librustc_ast}/ptr.rs | 0 src/{libsyntax => librustc_ast}/token.rs | 208 +- .../tokenstream.rs | 7 + .../util/classify.rs | 0 .../util/comments.rs | 11 +- .../util/comments/tests.rs | 0 .../util/lev_distance.rs | 0 .../util/lev_distance/tests.rs | 0 .../util/literal.rs | 4 +- .../util/map_in_place.rs | 0 .../util/parser.rs | 2 +- src/{libsyntax => librustc_ast}/visit.rs | 196 +- src/librustc_ast_lowering/Cargo.toml | 3 +- src/librustc_ast_lowering/expr.rs | 31 +- src/librustc_ast_lowering/item.rs | 241 +- src/librustc_ast_lowering/lib.rs | 125 +- src/librustc_ast_lowering/pat.rs | 4 +- src/librustc_ast_lowering/path.rs | 8 +- src/librustc_ast_passes/Cargo.toml | 4 +- src/librustc_ast_passes/ast_validation.rs | 631 +- src/librustc_ast_passes/feature_gate.rs | 99 +- src/librustc_ast_passes/lib.rs | 5 +- .../node_count.rs | 12 +- src/librustc_ast_passes/show_span.rs | 6 +- src/librustc_ast_pretty/Cargo.toml | 16 + .../print => librustc_ast_pretty}/helpers.rs | 2 +- src/librustc_ast_pretty/lib.rs | 7 + .../print => librustc_ast_pretty}/pp.rs | 0 .../print => librustc_ast_pretty}/pprust.rs | 396 +- .../pprust/tests.rs | 20 +- src/librustc_attr/Cargo.toml | 22 + src/librustc_attr/builtin.rs | 1072 ++ src/librustc_attr/lib.rs | 16 + src/librustc_builtin_macros/Cargo.toml | 4 +- src/librustc_builtin_macros/asm.rs | 28 +- src/librustc_builtin_macros/assert.rs | 24 +- src/librustc_builtin_macros/cfg.rs | 8 +- src/librustc_builtin_macros/cmdline_attrs.rs | 8 +- src/librustc_builtin_macros/compile_error.rs | 2 +- src/librustc_builtin_macros/concat.rs | 6 +- src/librustc_builtin_macros/concat_idents.rs | 8 +- .../deriving/bounds.rs | 2 +- src/librustc_builtin_macros/deriving/clone.rs | 4 +- .../deriving/cmp/eq.rs | 8 +- .../deriving/cmp/ord.rs | 4 +- .../deriving/cmp/partial_eq.rs | 4 +- .../deriving/cmp/partial_ord.rs | 4 +- src/librustc_builtin_macros/deriving/debug.rs | 6 +- .../deriving/decodable.rs | 6 +- .../deriving/default.rs | 4 +- .../deriving/encodable.rs | 4 +- .../deriving/generic/mod.rs | 59 +- .../deriving/generic/ty.rs | 4 +- src/librustc_builtin_macros/deriving/hash.rs | 4 +- src/librustc_builtin_macros/deriving/mod.rs | 8 +- src/librustc_builtin_macros/env.rs | 4 +- src/librustc_builtin_macros/format.rs | 91 +- .../global_allocator.rs | 21 +- src/librustc_builtin_macros/global_asm.rs | 8 +- src/librustc_builtin_macros/lib.rs | 2 +- src/librustc_builtin_macros/log_syntax.rs | 7 +- .../proc_macro_harness.rs | 75 +- src/librustc_builtin_macros/source_util.rs | 10 +- .../standard_library_imports.rs | 6 +- src/librustc_builtin_macros/test.rs | 179 +- src/librustc_builtin_macros/test_harness.rs | 40 +- src/librustc_builtin_macros/trace_macros.rs | 2 +- src/librustc_builtin_macros/util.rs | 2 +- src/librustc_codegen_llvm/Cargo.toml | 4 +- src/librustc_codegen_llvm/abi.rs | 2 +- src/librustc_codegen_llvm/allocator.rs | 2 +- src/librustc_codegen_llvm/asm.rs | 14 +- src/librustc_codegen_llvm/attributes.rs | 28 +- src/librustc_codegen_llvm/back/lto.rs | 184 +- src/librustc_codegen_llvm/back/profiling.rs | 58 + src/librustc_codegen_llvm/back/write.rs | 215 +- src/librustc_codegen_llvm/base.rs | 7 +- src/librustc_codegen_llvm/builder.rs | 41 +- src/librustc_codegen_llvm/common.rs | 3 +- src/librustc_codegen_llvm/consts.rs | 8 +- src/librustc_codegen_llvm/context.rs | 21 +- .../debuginfo/create_scope_map.rs | 10 +- src/librustc_codegen_llvm/debuginfo/gdb.rs | 2 +- .../debuginfo/metadata.rs | 281 +- src/librustc_codegen_llvm/debuginfo/mod.rs | 155 +- .../debuginfo/namespace.rs | 12 +- .../debuginfo/source_loc.rs | 90 +- src/librustc_codegen_llvm/declare.rs | 16 - src/librustc_codegen_llvm/intrinsic.rs | 4 +- src/librustc_codegen_llvm/lib.rs | 55 +- src/librustc_codegen_llvm/llvm/ffi.rs | 109 +- src/librustc_codegen_llvm/llvm/mod.rs | 1 + src/librustc_codegen_llvm/llvm_util.rs | 20 +- src/librustc_codegen_llvm/metadata.rs | 16 +- src/librustc_codegen_llvm/type_.rs | 2 +- src/librustc_codegen_llvm/va_arg.rs | 3 +- src/librustc_codegen_ssa/Cargo.toml | 3 +- src/librustc_codegen_ssa/back/link.rs | 125 +- src/librustc_codegen_ssa/back/linker.rs | 21 + .../back/symbol_export.rs | 2 +- src/librustc_codegen_ssa/back/write.rs | 42 +- src/librustc_codegen_ssa/base.rs | 37 +- src/librustc_codegen_ssa/build.rs | 4 + src/librustc_codegen_ssa/lib.rs | 5 - src/librustc_codegen_ssa/mir/analyze.rs | 27 +- src/librustc_codegen_ssa/mir/block.rs | 28 +- src/librustc_codegen_ssa/mir/constant.rs | 30 +- src/librustc_codegen_ssa/mir/debuginfo.rs | 228 +- src/librustc_codegen_ssa/mir/mod.rs | 20 +- src/librustc_codegen_ssa/mir/operand.rs | 25 +- src/librustc_codegen_ssa/mir/place.rs | 10 +- src/librustc_codegen_ssa/mir/rvalue.rs | 8 +- src/librustc_codegen_ssa/mir/statement.rs | 6 +- src/librustc_codegen_ssa/traits/backend.rs | 5 +- src/librustc_codegen_ssa/traits/builder.rs | 2 +- src/librustc_codegen_ssa/traits/debuginfo.rs | 30 +- src/librustc_codegen_ssa/traits/mod.rs | 3 +- src/librustc_codegen_utils/Cargo.toml | 2 +- src/librustc_codegen_utils/codegen_backend.rs | 13 +- src/librustc_codegen_utils/lib.rs | 4 - src/librustc_codegen_utils/link.rs | 4 +- src/librustc_codegen_utils/symbol_names.rs | 2 +- src/librustc_codegen_utils/symbol_names/v0.rs | 2 +- src/librustc_data_structures/box_region.rs | 39 + .../graph/vec_graph/tests.rs | 2 +- src/librustc_data_structures/lib.rs | 3 - src/librustc_data_structures/macros.rs | 38 + .../obligation_forest/graphviz.rs | 5 +- .../obligation_forest/mod.rs | 39 +- .../obligation_forest/tests.rs | 4 +- src/librustc_data_structures/profiling.rs | 129 +- src/librustc_data_structures/sharded.rs | 17 +- src/librustc_data_structures/sip128.rs | 121 +- src/librustc_data_structures/sorted_map.rs | 4 + .../sorted_map/index_map.rs | 218 + .../sorted_map/tests.rs | 28 +- src/librustc_data_structures/stable_hasher.rs | 1 + src/librustc_data_structures/sync.rs | 10 +- src/librustc_driver/Cargo.toml | 4 +- src/librustc_driver/args.rs | 2 +- src/librustc_driver/lib.rs | 72 +- src/librustc_driver/pretty.rs | 39 +- src/librustc_error_codes/error_codes.rs | 8 +- src/librustc_error_codes/error_codes/E0009.md | 6 +- src/librustc_error_codes/error_codes/E0080.md | 9 +- src/librustc_error_codes/error_codes/E0133.md | 4 +- src/librustc_error_codes/error_codes/E0154.md | 7 +- src/librustc_error_codes/error_codes/E0260.md | 7 +- src/librustc_error_codes/error_codes/E0263.md | 17 +- src/librustc_error_codes/error_codes/E0264.md | 4 +- src/librustc_error_codes/error_codes/E0267.md | 6 +- src/librustc_error_codes/error_codes/E0268.md | 7 +- src/librustc_error_codes/error_codes/E0271.md | 12 +- src/librustc_error_codes/error_codes/E0275.md | 10 +- src/librustc_error_codes/error_codes/E0276.md | 5 +- src/librustc_error_codes/error_codes/E0277.md | 4 +- src/librustc_error_codes/error_codes/E0282.md | 18 +- src/librustc_error_codes/error_codes/E0283.md | 9 +- src/librustc_error_codes/error_codes/E0303.md | 4 +- src/librustc_error_codes/error_codes/E0307.md | 20 +- src/librustc_error_codes/error_codes/E0309.md | 22 +- src/librustc_error_codes/error_codes/E0310.md | 13 +- src/librustc_error_codes/error_codes/E0317.md | 30 +- src/librustc_error_codes/error_codes/E0321.md | 4 +- src/librustc_error_codes/error_codes/E0322.md | 10 + src/librustc_error_codes/error_codes/E0323.md | 1 + src/librustc_error_codes/error_codes/E0324.md | 5 +- src/librustc_error_codes/error_codes/E0325.md | 1 + src/librustc_error_codes/error_codes/E0326.md | 8 +- src/librustc_error_codes/error_codes/E0364.md | 6 +- src/librustc_error_codes/error_codes/E0365.md | 6 +- src/librustc_error_codes/error_codes/E0367.md | 5 +- src/librustc_error_codes/error_codes/E0368.md | 6 +- src/librustc_error_codes/error_codes/E0369.md | 1 + src/librustc_error_codes/error_codes/E0370.md | 4 +- src/librustc_error_codes/error_codes/E0371.md | 12 +- src/librustc_error_codes/error_codes/E0373.md | 10 +- src/librustc_error_codes/error_codes/E0374.md | 14 +- src/librustc_error_codes/error_codes/E0375.md | 19 +- src/librustc_error_codes/error_codes/E0376.md | 21 +- src/librustc_error_codes/error_codes/E0378.md | 42 +- src/librustc_error_codes/error_codes/E0379.md | 12 + src/librustc_error_codes/error_codes/E0380.md | 14 +- src/librustc_error_codes/error_codes/E0382.md | 9 +- src/librustc_error_codes/error_codes/E0384.md | 2 +- src/librustc_error_codes/error_codes/E0387.md | 4 +- src/librustc_error_codes/error_codes/E0390.md | 4 +- src/librustc_error_codes/error_codes/E0391.md | 8 +- src/librustc_error_codes/error_codes/E0392.md | 5 +- src/librustc_error_codes/error_codes/E0393.md | 3 +- src/librustc_error_codes/error_codes/E0399.md | 4 +- src/librustc_error_codes/error_codes/E0454.md | 2 +- src/librustc_error_codes/error_codes/E0455.md | 6 +- src/librustc_error_codes/error_codes/E0458.md | 2 +- src/librustc_error_codes/error_codes/E0459.md | 2 +- src/librustc_error_codes/error_codes/E0499.md | 10 +- src/librustc_error_codes/error_codes/E0501.md | 7 +- src/librustc_error_codes/error_codes/E0502.md | 6 +- src/librustc_error_codes/error_codes/E0503.md | 6 +- src/librustc_error_codes/error_codes/E0505.md | 6 +- src/librustc_error_codes/error_codes/E0507.md | 6 +- src/librustc_error_codes/error_codes/E0511.md | 2 +- src/librustc_error_codes/error_codes/E0525.md | 6 +- src/librustc_error_codes/error_codes/E0534.md | 8 +- src/librustc_error_codes/error_codes/E0535.md | 8 +- src/librustc_error_codes/error_codes/E0536.md | 6 +- src/librustc_error_codes/error_codes/E0537.md | 6 +- src/librustc_error_codes/error_codes/E0565.md | 14 +- src/librustc_error_codes/error_codes/E0591.md | 2 +- src/librustc_error_codes/error_codes/E0601.md | 6 +- src/librustc_error_codes/error_codes/E0610.md | 7 +- src/librustc_error_codes/error_codes/E0626.md | 10 +- src/librustc_error_codes/error_codes/E0633.md | 4 +- src/librustc_error_codes/error_codes/E0637.md | 32 + src/librustc_error_codes/error_codes/E0660.md | 7 +- src/librustc_error_codes/error_codes/E0661.md | 7 +- src/librustc_error_codes/error_codes/E0662.md | 7 +- src/librustc_error_codes/error_codes/E0663.md | 7 +- src/librustc_error_codes/error_codes/E0664.md | 7 +- src/librustc_error_codes/error_codes/E0668.md | 2 +- src/librustc_error_codes/error_codes/E0719.md | 35 + src/librustc_error_codes/error_codes/E0727.md | 26 + src/librustc_error_codes/error_codes/E0747.md | 20 + src/librustc_error_codes/error_codes/E0748.md | 16 + src/librustc_error_codes/lib.rs | 5 +- src/librustc_errors/Cargo.toml | 2 +- .../annotate_snippet_emitter_writer.rs | 10 +- src/librustc_errors/diagnostic.rs | 7 +- src/librustc_errors/diagnostic_builder.rs | 23 +- src/librustc_errors/emitter.rs | 240 +- src/librustc_errors/json.rs | 44 +- src/librustc_errors/lib.rs | 52 +- src/librustc_errors/registry.rs | 24 +- src/librustc_errors/snippet.rs | 2 +- src/librustc_expand/Cargo.toml | 4 +- src/librustc_expand/base.rs | 89 +- src/librustc_expand/build.rs | 19 +- src/librustc_expand/expand.rs | 340 +- src/librustc_expand/lib.rs | 1 + src/librustc_expand/mbe.rs | 6 +- src/librustc_expand/mbe/macro_check.rs | 8 +- src/librustc_expand/mbe/macro_parser.rs | 79 +- src/librustc_expand/mbe/macro_rules.rs | 87 +- src/librustc_expand/mbe/quoted.rs | 14 +- src/librustc_expand/mbe/transcribe.rs | 17 +- src/librustc_expand/mut_visit/tests.rs | 8 +- src/librustc_expand/parse/lexer/tests.rs | 8 +- src/librustc_expand/parse/tests.rs | 18 +- src/librustc_expand/placeholders.rs | 48 +- src/librustc_expand/proc_macro.rs | 6 +- src/librustc_expand/proc_macro_server.rs | 30 +- src/librustc_expand/tests.rs | 8 +- src/librustc_expand/tokenstream/tests.rs | 8 +- src/librustc_feature/active.rs | 32 +- src/librustc_feature/builtin_attrs.rs | 21 +- src/librustc_feature/removed.rs | 6 +- src/librustc_hir/Cargo.toml | 5 +- src/librustc_hir/def.rs | 4 +- src/librustc_hir/hir.rs | 167 +- src/librustc_hir/intravisit.rs | 8 +- src/librustc_hir/lang_items.rs | 261 + src/librustc_hir/lib.rs | 8 +- src/librustc_hir/pat_util.rs | 2 +- src/librustc_hir/print.rs | 33 +- src/librustc_hir/stable_hash_impls.rs | 29 +- src/librustc_hir/target.rs | 125 + src/librustc_hir/weak_lang_items.rs | 48 + src/librustc_incremental/Cargo.toml | 2 +- src/librustc_incremental/assert_dep_graph.rs | 6 +- .../assert_module_sources.rs | 9 +- src/librustc_incremental/lib.rs | 1 - .../persist/dirty_clean.rs | 14 +- .../persist/file_format.rs | 3 +- src/librustc_incremental/persist/fs.rs | 6 +- .../persist/work_product.rs | 4 +- src/librustc_index/vec.rs | 8 + src/librustc_infer/Cargo.toml | 28 + src/{librustc => librustc_infer}/infer/at.rs | 6 +- .../infer/canonical/canonicalizer.rs | 45 +- src/librustc_infer/infer/canonical/mod.rs | 163 + .../infer/canonical/query_response.rs | 99 +- .../infer/canonical/substitute.rs | 35 +- .../infer/combine.rs | 64 +- .../infer/equate.rs | 33 +- .../infer/error_reporting/mod.rs | 2106 ++++ .../infer/error_reporting/need_type_info.rs | 27 +- .../nice_region_error/different_lifetimes.rs | 4 +- .../nice_region_error/find_anon_type.rs | 6 +- .../error_reporting/nice_region_error/mod.rs | 87 + .../nice_region_error/named_anon_conflict.rs | 8 +- .../nice_region_error/outlives_closure.rs | 4 +- .../nice_region_error/placeholder_error.rs | 27 +- .../nice_region_error/static_impl_trait.rs | 4 +- .../trait_impl_difference.rs | 4 +- .../error_reporting/nice_region_error/util.rs | 132 + .../infer/error_reporting/note.rs | 11 +- .../infer/freshen.rs | 29 +- .../infer/fudge.rs | 36 +- src/{librustc => librustc_infer}/infer/glb.rs | 13 +- .../infer/higher_ranked/README.md | 0 src/librustc_infer/infer/higher_ranked/mod.rs | 148 + .../infer/lattice.rs | 10 +- .../infer/lexical_region_resolve/README.md | 0 .../infer/lexical_region_resolve/graphviz.rs | 6 +- .../infer/lexical_region_resolve/mod.rs | 1029 ++ src/{librustc => librustc_infer}/infer/lub.rs | 13 +- src/librustc_infer/infer/mod.rs | 1816 +++ src/librustc_infer/infer/nll_relate/mod.rs | 1007 ++ src/librustc_infer/infer/opaque_types/mod.rs | 1328 ++ .../infer/outlives/env.rs | 4 +- .../infer/outlives/mod.rs | 0 .../infer/outlives/obligations.rs | 12 +- .../infer/outlives/verify.rs | 20 +- .../infer/region_constraints/README.md | 0 .../infer/region_constraints/leak_check.rs | 20 +- .../infer/region_constraints/mod.rs | 918 ++ .../infer/resolve.rs | 23 +- src/{librustc => librustc_infer}/infer/sub.rs | 23 +- .../infer/type_variable.rs | 17 +- src/librustc_infer/lib.rs | 38 + .../traits/auto_trait.rs | 28 +- src/librustc_infer/traits/codegen/mod.rs | 114 + .../traits/coherence.rs | 57 +- .../traits/engine.rs | 12 +- .../traits/error_reporting/mod.rs | 1643 +++ .../error_reporting/on_unimplemented.rs | 223 + .../traits/error_reporting/suggestions.rs | 119 +- .../traits/fulfill.rs | 56 +- src/librustc_infer/traits/misc.rs | 71 + src/librustc_infer/traits/mod.rs | 642 + src/librustc_infer/traits/object_safety.rs | 777 ++ src/librustc_infer/traits/on_unimplemented.rs | 383 + .../traits/project.rs | 211 +- .../traits/query/dropck_outlives.rs | 137 + .../traits/query/evaluate_obligation.rs | 0 .../traits/query/method_autoderef.rs | 1 + src/librustc_infer/traits/query/mod.rs | 15 + src/librustc_infer/traits/query/normalize.rs | 189 + .../traits/query/outlives_bounds.rs | 103 + .../traits/query/type_op/ascribe_user_type.rs | 23 + .../traits/query/type_op/custom.rs | 0 src/librustc_infer/traits/query/type_op/eq.rs | 23 + .../query/type_op/implied_outlives_bounds.rs | 2 +- .../traits/query/type_op/mod.rs | 136 + .../traits/query/type_op/normalize.rs | 68 + .../traits/query/type_op/outlives.rs | 2 +- .../traits/query/type_op/prove_predicate.rs | 13 +- .../traits/query/type_op/subtype.rs | 20 + src/librustc_infer/traits/select.rs | 3823 ++++++ src/librustc_infer/traits/specialize/mod.rs | 472 + .../traits/specialize/specialization_graph.rs | 379 + src/librustc_infer/traits/structural_impls.rs | 71 + .../traits/structural_match.rs | 9 +- src/librustc_infer/traits/util.rs | 675 ++ src/{librustc => librustc_infer}/traits/wf.rs | 49 +- src/librustc_interface/Cargo.toml | 4 +- src/librustc_interface/callbacks.rs | 6 +- src/librustc_interface/interface.rs | 25 +- src/librustc_interface/lib.rs | 2 - src/librustc_interface/passes.rs | 35 +- src/librustc_interface/proc_macro_decls.rs | 2 +- src/librustc_interface/queries.rs | 45 +- src/librustc_interface/tests.rs | 11 +- src/librustc_interface/util.rs | 45 +- src/librustc_lexer/src/lib.rs | 2 +- src/librustc_lexer/src/unescape.rs | 4 +- src/librustc_lint/Cargo.toml | 5 +- src/librustc_lint/array_into_iter.rs | 7 +- src/librustc_lint/builtin.rs | 704 +- src/librustc_lint/context.rs | 239 +- src/librustc_lint/early.rs | 68 +- src/librustc_lint/internal.rs | 114 +- src/librustc_lint/late.rs | 25 +- src/librustc_lint/levels.rs | 125 +- src/librustc_lint/lib.rs | 70 +- src/librustc_lint/non_ascii_idents.rs | 20 +- src/librustc_lint/nonstandard_style.rs | 83 +- src/librustc_lint/passes.rs | 7 +- src/librustc_lint/redundant_semicolon.rs | 63 +- src/librustc_lint/types.rs | 223 +- src/librustc_lint/unused.rs | 196 +- src/librustc_llvm/build.rs | 2 +- src/librustc_macros/Cargo.toml | 1 - src/librustc_macros/src/hash_stable.rs | 1 - src/librustc_macros/src/lib.rs | 2 - src/librustc_macros/src/lift.rs | 2 - src/librustc_macros/src/query.rs | 105 +- src/librustc_macros/src/symbols.rs | 1 - src/librustc_macros/src/type_foldable.rs | 2 - src/librustc_metadata/Cargo.toml | 4 +- src/librustc_metadata/creader.rs | 46 +- src/librustc_metadata/dependency_format.rs | 2 +- src/librustc_metadata/lib.rs | 5 - src/librustc_metadata/locator.rs | 2 +- src/librustc_metadata/native_libs.rs | 2 +- src/librustc_metadata/rmeta/decoder.rs | 254 +- .../rmeta/decoder/cstore_impl.rs | 23 +- src/librustc_metadata/rmeta/encoder.rs | 41 +- src/librustc_metadata/rmeta/mod.rs | 11 +- src/librustc_mir/Cargo.toml | 7 +- .../borrow_check/constraint_generation.rs | 10 +- .../diagnostics/conflict_errors.rs | 91 +- .../diagnostics/explain_borrow.rs | 2 +- .../borrow_check/diagnostics/mod.rs | 46 +- .../borrow_check/diagnostics/move_errors.rs | 15 +- .../diagnostics/mutability_errors.rs | 223 +- .../borrow_check/diagnostics/region_errors.rs | 51 +- .../borrow_check/diagnostics/region_name.rs | 6 +- src/librustc_mir/borrow_check/facts.rs | 54 +- src/librustc_mir/borrow_check/flows.rs | 142 - src/librustc_mir/borrow_check/invalidation.rs | 10 +- .../borrow_check/member_constraints.rs | 4 +- src/librustc_mir/borrow_check/mod.rs | 384 +- src/librustc_mir/borrow_check/nll.rs | 88 +- src/librustc_mir/borrow_check/place_ext.rs | 2 +- .../borrow_check/places_conflict.rs | 10 +- src/librustc_mir/borrow_check/prefixes.rs | 14 +- .../borrow_check/region_infer/dump_mir.rs | 2 +- .../borrow_check/region_infer/mod.rs | 71 +- .../borrow_check/region_infer/opaque_types.rs | 149 + .../borrow_check/region_infer/reverse_sccs.rs | 68 + .../borrow_check/region_infer/values.rs | 2 +- src/librustc_mir/borrow_check/renumber.rs | 2 +- .../type_check/constraint_conversion.rs | 18 +- .../type_check/free_region_relations.rs | 21 +- .../borrow_check/type_check/input_output.rs | 2 +- .../borrow_check/type_check/liveness/mod.rs | 6 +- .../type_check/liveness/polonius.rs | 45 +- .../borrow_check/type_check/liveness/trace.rs | 50 +- .../borrow_check/type_check/mod.rs | 181 +- .../borrow_check/type_check/relate_tys.rs | 10 +- .../borrow_check/universal_regions.rs | 31 +- src/librustc_mir/const_eval.rs | 92 - src/librustc_mir/const_eval/error.rs | 28 +- src/librustc_mir/const_eval/eval_queries.rs | 49 +- src/librustc_mir/const_eval/fn_queries.rs | 132 +- src/librustc_mir/const_eval/machine.rs | 106 +- src/librustc_mir/const_eval/mod.rs | 87 + src/librustc_mir/dataflow/at_location.rs | 41 - src/librustc_mir/dataflow/generic/cursor.rs | 7 + src/librustc_mir/dataflow/generic/engine.rs | 131 +- src/librustc_mir/dataflow/generic/graphviz.rs | 132 +- src/librustc_mir/dataflow/generic/mod.rs | 97 + src/librustc_mir/dataflow/generic/visitor.rs | 272 + src/librustc_mir/dataflow/graphviz.rs | 2 +- .../dataflow/impls/borrowed_locals.rs | 292 +- src/librustc_mir/dataflow/impls/borrows.rs | 96 +- .../dataflow/impls/indirect_mutation.rs | 136 - src/librustc_mir/dataflow/impls/mod.rs | 254 +- .../dataflow/impls/storage_liveness.rs | 285 +- src/librustc_mir/dataflow/mod.rs | 18 +- .../dataflow/move_paths/builder.rs | 10 +- src/librustc_mir/dataflow/move_paths/mod.rs | 99 +- src/librustc_mir/interpret/cast.rs | 4 +- src/librustc_mir/interpret/eval_context.rs | 30 +- src/librustc_mir/interpret/intern.rs | 20 +- src/librustc_mir/interpret/intrinsics.rs | 85 +- .../interpret/intrinsics/caller_location.rs | 12 +- src/librustc_mir/interpret/machine.rs | 51 +- src/librustc_mir/interpret/memory.rs | 98 +- src/librustc_mir/interpret/operand.rs | 73 +- src/librustc_mir/interpret/operator.rs | 78 +- src/librustc_mir/interpret/place.rs | 10 +- src/librustc_mir/interpret/snapshot.rs | 4 +- src/librustc_mir/interpret/step.rs | 5 +- src/librustc_mir/interpret/terminator.rs | 11 +- src/librustc_mir/interpret/validity.rs | 549 +- src/librustc_mir/interpret/visitor.rs | 120 +- src/librustc_mir/lib.rs | 9 +- src/librustc_mir/monomorphize/collector.rs | 45 +- src/librustc_mir/monomorphize/mod.rs | 4 +- src/librustc_mir/monomorphize/partitioning.rs | 13 +- src/librustc_mir/shim.rs | 3 +- src/librustc_mir/transform/add_retag.rs | 8 +- .../transform/check_consts/ops.rs | 6 +- .../transform/check_consts/qualifs.rs | 55 +- .../transform/check_consts/resolver.rs | 18 +- .../transform/check_consts/validation.rs | 145 +- src/librustc_mir/transform/check_unsafety.rs | 171 +- src/librustc_mir/transform/const_prop.rs | 295 +- src/librustc_mir/transform/dump_mir.rs | 2 +- src/librustc_mir/transform/elaborate_drops.rs | 153 +- src/librustc_mir/transform/generator.rs | 252 +- src/librustc_mir/transform/inline.rs | 33 +- src/librustc_mir/transform/mod.rs | 6 +- src/librustc_mir/transform/promote_consts.rs | 25 +- .../transform/qualify_min_const_fn.rs | 14 +- src/librustc_mir/transform/rustc_peek.rs | 86 +- src/librustc_mir/transform/simplify.rs | 2 +- src/librustc_mir/transform/simplify_try.rs | 5 +- .../transform/uninhabited_enum_branching.rs | 4 +- src/librustc_mir/util/aggregate.rs | 1 - src/librustc_mir/util/alignment.rs | 2 +- src/librustc_mir/util/elaborate_drops.rs | 55 +- src/librustc_mir/util/liveness.rs | 5 +- src/librustc_mir/util/patch.rs | 2 +- src/librustc_mir/util/pretty.rs | 6 +- src/librustc_mir_build/Cargo.toml | 5 +- src/librustc_mir_build/build/block.rs | 2 +- src/librustc_mir_build/build/expr/as_place.rs | 8 +- .../build/expr/as_rvalue.rs | 36 +- src/librustc_mir_build/build/expr/category.rs | 2 +- src/librustc_mir_build/build/expr/into.rs | 21 +- src/librustc_mir_build/build/matches/mod.rs | 862 +- .../build/matches/simplify.rs | 56 +- src/librustc_mir_build/build/matches/test.rs | 49 +- src/librustc_mir_build/build/mod.rs | 86 +- src/librustc_mir_build/hair/constant.rs | 4 +- src/librustc_mir_build/hair/cx/block.rs | 2 +- src/librustc_mir_build/hair/cx/expr.rs | 35 +- src/librustc_mir_build/hair/cx/mod.rs | 28 +- src/librustc_mir_build/hair/mod.rs | 11 - src/librustc_mir_build/hair/pattern/_match.rs | 79 +- .../hair/pattern/check_match.rs | 255 +- .../hair/pattern/const_to_pat.rs | 29 +- src/librustc_mir_build/hair/pattern/mod.rs | 11 +- src/librustc_mir_build/lib.rs | 1 - src/librustc_mir_build/lints.rs | 23 +- src/librustc_parse/Cargo.toml | 4 +- src/librustc_parse/config.rs | 129 +- src/librustc_parse/lexer/mod.rs | 36 +- src/librustc_parse/lexer/tokentrees.rs | 30 +- .../lexer/unescape_error_reporting.rs | 2 +- src/librustc_parse/lib.rs | 32 +- src/librustc_parse/parser/attr.rs | 26 +- src/librustc_parse/parser/diagnostics.rs | 170 +- src/librustc_parse/parser/expr.rs | 368 +- src/librustc_parse/parser/generics.rs | 51 +- src/librustc_parse/parser/item.rs | 1778 ++- src/librustc_parse/parser/mod.rs | 392 +- src/librustc_parse/parser/module.rs | 42 +- src/librustc_parse/parser/pat.rs | 85 +- src/librustc_parse/parser/path.rs | 81 +- src/librustc_parse/parser/stmt.rs | 305 +- src/librustc_parse/parser/ty.rs | 132 +- src/librustc_parse/validate_attr.rs | 14 +- src/librustc_passes/Cargo.toml | 4 +- src/librustc_passes/check_attr.rs | 481 + src/librustc_passes/check_const.rs | 7 +- src/librustc_passes/dead.rs | 22 +- src/librustc_passes/diagnostic_items.rs | 6 +- src/librustc_passes/entry.rs | 12 +- src/librustc_passes/hir_stats.rs | 25 +- src/librustc_passes/lang_items.rs | 174 + src/librustc_passes/layout_test.rs | 2 +- src/librustc_passes/lib.rs | 8 +- src/librustc_passes/lib_features.rs | 2 +- src/librustc_passes/liveness.rs | 138 +- src/librustc_passes/loops.rs | 2 +- src/librustc_passes/reachable.rs | 12 +- src/librustc_passes/region.rs | 6 +- src/librustc_passes/stability.rs | 318 +- .../hir => librustc_passes}/upvars.rs | 6 +- src/librustc_passes/weak_lang_items.rs | 103 + src/librustc_plugin_impl/Cargo.toml | 2 +- src/librustc_plugin_impl/build.rs | 2 +- src/librustc_plugin_impl/load.rs | 2 +- src/librustc_privacy/Cargo.toml | 3 +- src/librustc_privacy/lib.rs | 37 +- src/librustc_resolve/Cargo.toml | 5 +- src/librustc_resolve/build_reduced_graph.rs | 118 +- src/librustc_resolve/check_unused.rs | 44 +- src/librustc_resolve/def_collector.rs | 55 +- src/librustc_resolve/diagnostics.rs | 139 +- src/librustc_resolve/imports.rs | 383 +- src/librustc_resolve/late.rs | 241 +- src/librustc_resolve/late/diagnostics.rs | 281 +- src/librustc_resolve/{ => late}/lifetimes.rs | 187 +- src/librustc_resolve/lib.rs | 124 +- src/librustc_resolve/macros.rs | 6 +- src/librustc_save_analysis/Cargo.toml | 3 +- src/librustc_save_analysis/dump_visitor.rs | 99 +- src/librustc_save_analysis/lib.rs | 68 +- src/librustc_save_analysis/sig.rs | 72 +- src/librustc_save_analysis/span_utils.rs | 2 +- src/librustc_session/Cargo.toml | 1 + src/librustc_session/code_stats.rs | 2 +- src/librustc_session/config.rs | 50 +- src/librustc_session/lib.rs | 1 - src/librustc_session/lint.rs | 3 +- src/librustc_session/lint/builtin.rs | 39 +- src/librustc_session/node_id.rs | 40 - src/librustc_session/options.rs | 32 +- src/librustc_session/parse.rs | 36 +- src/librustc_session/session.rs | 26 +- src/librustc_span/caching_source_map_view.rs | 8 +- src/{librustc_hir => librustc_span}/def_id.rs | 28 +- src/librustc_span/lib.rs | 20 +- src/librustc_span/source_map.rs | 82 +- src/librustc_span/symbol.rs | 97 +- src/librustc_target/abi/call/aarch64.rs | 2 +- src/librustc_target/abi/call/arm.rs | 2 +- src/librustc_target/abi/call/mod.rs | 173 +- src/librustc_target/abi/call/powerpc64.rs | 2 +- src/librustc_target/abi/call/riscv.rs | 335 +- src/librustc_target/abi/call/sparc64.rs | 2 +- src/librustc_target/abi/call/wasm32.rs | 2 +- src/librustc_target/abi/call/x86.rs | 2 +- src/librustc_target/abi/call/x86_64.rs | 24 +- src/librustc_target/abi/mod.rs | 28 +- src/librustc_target/lib.rs | 2 - src/librustc_target/spec/apple_base.rs | 2 +- .../spec/i686_pc_windows_gnu.rs | 1 + src/librustc_target/spec/i686_unknown_uefi.rs | 4 +- .../spec/nvptx64_nvidia_cuda.rs | 4 +- src/librustc_target/spec/thumb_base.rs | 3 + src/librustc_target/spec/windows_msvc_base.rs | 7 +- .../spec/x86_64_pc_windows_gnu.rs | 1 + src/librustc_traits/Cargo.toml | 4 +- src/librustc_traits/chalk_context/mod.rs | 638 - .../chalk_context/program_clauses/builtin.rs | 316 - .../chalk_context/program_clauses/mod.rs | 300 - .../program_clauses/primitive.rs | 168 - .../chalk_context/resolvent_ops.rs | 293 - src/librustc_traits/chalk_context/unify.rs | 85 - src/librustc_traits/dropck_outlives.rs | 18 +- src/librustc_traits/evaluate_obligation.rs | 9 +- src/librustc_traits/generic_types.rs | 67 - .../implied_outlives_bounds.rs | 16 +- src/librustc_traits/lib.rs | 3 - src/librustc_traits/lowering/environment.rs | 2 +- src/librustc_traits/lowering/mod.rs | 4 +- .../normalize_erasing_regions.rs | 3 +- .../normalize_projection_ty.rs | 9 +- src/librustc_traits/type_op.rs | 20 +- src/librustc_ty/Cargo.toml | 2 + src/librustc_ty/common_traits.rs | 41 + src/librustc_ty/instance.rs | 136 + src/librustc_ty/lib.rs | 7 +- src/librustc_ty/needs_drop.rs | 165 + src/librustc_ty/ty.rs | 23 +- src/librustc_typeck/Cargo.toml | 4 +- src/librustc_typeck/astconv.rs | 444 +- src/librustc_typeck/check/_match.rs | 6 +- src/librustc_typeck/check/autoderef.rs | 10 +- src/librustc_typeck/check/callee.rs | 6 +- src/librustc_typeck/check/cast.rs | 32 +- src/librustc_typeck/check/closure.rs | 41 +- src/librustc_typeck/check/coercion.rs | 15 +- src/librustc_typeck/check/compare_method.rs | 4 +- src/librustc_typeck/check/demand.rs | 60 +- src/librustc_typeck/check/dropck.rs | 7 +- src/librustc_typeck/check/expr.rs | 28 +- .../check/generator_interior.rs | 48 +- src/librustc_typeck/check/method/confirm.rs | 42 +- src/librustc_typeck/check/method/mod.rs | 62 +- src/librustc_typeck/check/method/probe.rs | 303 +- src/librustc_typeck/check/method/suggest.rs | 338 +- src/librustc_typeck/check/mod.rs | 387 +- src/librustc_typeck/check/op.rs | 94 +- src/librustc_typeck/check/pat.rs | 295 +- src/librustc_typeck/check/regionck.rs | 4 +- src/librustc_typeck/check/upvar.rs | 4 +- src/librustc_typeck/check/wfcheck.rs | 220 +- src/librustc_typeck/check/writeback.rs | 9 +- src/librustc_typeck/check_unused.rs | 87 +- src/librustc_typeck/coherence/builtin.rs | 24 +- .../coherence/inherent_impls.rs | 8 +- .../coherence/inherent_impls_overlap.rs | 138 +- src/librustc_typeck/coherence/mod.rs | 86 +- src/librustc_typeck/coherence/orphan.rs | 9 +- src/librustc_typeck/collect.rs | 949 +- src/librustc_typeck/collect/type_of.rs | 661 + src/librustc_typeck/expr_use_visitor.rs | 2 +- src/librustc_typeck/impl_wf_check.rs | 21 +- src/librustc_typeck/lib.rs | 10 +- src/librustc_typeck/mem_categorization.rs | 3 +- src/librustc_typeck/namespace.rs | 27 - .../outlives/implicit_infer.rs | 6 +- src/librustc_typeck/outlives/mod.rs | 2 +- src/librustc_typeck/outlives/utils.rs | 2 +- src/librustc_typeck/variance/constraints.rs | 2 +- src/librustc_typeck/variance/mod.rs | 3 +- src/librustdoc/Cargo.toml | 2 +- src/librustdoc/clean/auto_trait.rs | 4 +- src/librustdoc/clean/blanket_impl.rs | 6 +- src/librustdoc/clean/cfg.rs | 4 +- src/librustdoc/clean/cfg/tests.rs | 6 +- src/librustdoc/clean/inline.rs | 50 +- src/librustdoc/clean/mod.rs | 56 +- src/librustdoc/clean/types.rs | 41 +- src/librustdoc/clean/utils.rs | 41 +- src/librustdoc/config.rs | 7 +- src/librustdoc/core.rs | 14 +- src/librustdoc/docfs.rs | 12 +- src/librustdoc/doctree.rs | 8 +- src/librustdoc/html/format.rs | 27 +- src/librustdoc/html/highlight.rs | 23 +- src/librustdoc/html/item_type.rs | 10 +- src/librustdoc/html/markdown.rs | 192 +- src/librustdoc/html/render.rs | 123 +- src/librustdoc/html/render/cache.rs | 33 +- src/librustdoc/html/static/brush.svg | 2 +- src/librustdoc/html/static/down-arrow.svg | 2 +- src/librustdoc/html/static/main.js | 58 +- src/librustdoc/html/static/rustdoc.css | 100 +- src/librustdoc/html/static/themes/dark.css | 33 - src/librustdoc/html/static/themes/light.css | 33 - src/librustdoc/html/static/wheel.svg | 2 +- src/librustdoc/lib.rs | 9 +- src/librustdoc/markdown.rs | 3 +- .../passes/calculate_doc_coverage.rs | 2 +- .../passes/check_code_block_syntax.rs | 8 +- .../passes/collect_intra_doc_links.rs | 285 +- src/librustdoc/passes/mod.rs | 19 +- src/librustdoc/test.rs | 25 +- src/librustdoc/theme.rs | 35 +- src/librustdoc/theme/tests.rs | 13 + src/librustdoc/visit_ast.rs | 2 +- src/libserialize/leb128.rs | 64 +- src/libserialize/lib.rs | 1 - src/libserialize/opaque.rs | 12 +- src/libserialize/serialize.rs | 19 + src/libstd/Cargo.toml | 2 +- src/libstd/alloc.rs | 47 +- src/libstd/backtrace.rs | 71 +- src/libstd/collections/hash/map.rs | 128 +- src/libstd/collections/hash/set.rs | 20 +- src/libstd/f32.rs | 3 + src/libstd/f64.rs | 3 + src/libstd/ffi/c_str.rs | 27 + src/libstd/fs.rs | 14 +- src/libstd/future.rs | 8 +- src/libstd/io/buffered.rs | 45 + src/libstd/io/cursor.rs | 2 +- src/libstd/io/mod.rs | 12 +- src/libstd/io/stdio.rs | 2 +- src/libstd/keyword_docs.rs | 58 +- src/libstd/lib.rs | 18 +- src/libstd/macros.rs | 23 +- src/libstd/net/addr.rs | 2 +- src/libstd/net/ip.rs | 74 +- src/libstd/net/parser.rs | 2 +- src/libstd/os/linux/fs.rs | 2 +- src/libstd/panicking.rs | 4 +- src/libstd/path.rs | 2 +- src/libstd/primitive_docs.rs | 28 +- src/libstd/sync/mpsc/spsc_queue.rs | 2 +- src/libstd/sync/mutex.rs | 2 +- src/libstd/sync/once.rs | 11 +- src/libstd/sync/rwlock.rs | 7 +- src/libstd/sys/sgx/abi/entry.S | 40 +- src/libstd/sys/sgx/abi/usercalls/alloc.rs | 2 +- src/libstd/sys/sgx/args.rs | 7 +- src/libstd/sys/sgx/rwlock.rs | 24 +- src/libstd/sys/unix/mod.rs | 2 +- src/libstd/sys/unix/net.rs | 2 +- src/libstd/sys/unix/process/process_common.rs | 8 +- src/libstd/sys/unix/stack_overflow.rs | 28 +- src/libstd/sys/unix/thread.rs | 9 +- src/libstd/sys/unix/time.rs | 1 - src/libstd/sys/vxworks/mod.rs | 2 +- src/libstd/sys/wasi/fd.rs | 12 +- src/libstd/sys/wasi/fs.rs | 10 +- src/libstd/sys_common/backtrace.rs | 1 + src/libstd/tests/run-time-detect.rs | 1 + src/libstd/time.rs | 6 +- src/libsyntax/Cargo.toml | 24 - src/libsyntax/README.md | 9 - src/libsyntax/attr/builtin.rs | 1032 -- src/libsyntax/attr/mod.rs | 737 -- src/libsyntax/lib.rs | 104 - src/libtest/cli.rs | 5 +- src/libtest/console.rs | 2 - src/libtest/formatters/json.rs | 2 +- src/libtest/lib.rs | 32 +- src/libtest/options.rs | 2 +- src/libtest/test_result.rs | 4 +- src/rustllvm/ArchiveWrapper.cpp | 3 + src/rustllvm/PassWrapper.cpp | 336 +- src/rustllvm/RustWrapper.cpp | 160 +- src/stage0.txt | 15 +- src/stdarch/.github/workflows/main.yml | 209 + src/stdarch/QUESTIONS.md | 31 - src/stdarch/README.md | 5 +- src/stdarch/ci/azure-install-rust.yml | 76 - src/stdarch/ci/azure.yml | 221 - .../mipsel-unknown-linux-musl/Dockerfile | 4 +- src/stdarch/ci/dox.sh | 2 + src/stdarch/ci/style.sh | 8 +- .../crates/assert-instr-macro/Cargo.toml | 6 +- .../crates/assert-instr-macro/src/lib.rs | 30 +- src/stdarch/crates/core_arch/Cargo.toml | 1 - src/stdarch/crates/core_arch/README.md | 4 +- src/stdarch/crates/core_arch/rustfmt.toml | 3 + src/stdarch/crates/core_arch/src/arm/neon.rs | 4 +- src/stdarch/crates/core_arch/src/mips/msa.rs | 6 +- src/stdarch/crates/core_arch/src/simd.rs | 1 - src/stdarch/crates/core_arch/src/simd_llvm.rs | 30 + .../crates/core_arch/src/wasm32/simd128.rs | 2 +- src/stdarch/crates/core_arch/src/x86/avx.rs | 28 +- src/stdarch/crates/core_arch/src/x86/avx2.rs | 32 +- src/stdarch/crates/core_arch/src/x86/bswap.rs | 8 +- src/stdarch/crates/core_arch/src/x86/fma.rs | 17 +- src/stdarch/crates/core_arch/src/x86/mod.rs | 49 +- src/stdarch/crates/core_arch/src/x86/sse.rs | 17 + src/stdarch/crates/core_arch/src/x86/sse2.rs | 34 +- src/stdarch/crates/core_arch/src/x86/sse41.rs | 18 +- .../crates/core_arch/src/x86_64/bswap.rs | 8 +- .../crates/core_arch/tests/cpu-detection.rs | 17 + src/stdarch/crates/simd-test-macro/Cargo.toml | 4 +- src/stdarch/crates/std_detect/Cargo.toml | 8 +- src/stdarch/crates/std_detect/README.md | 4 +- .../std_detect/src/detect/arch/aarch64.rs | 114 +- .../crates/std_detect/src/detect/arch/arm.rs | 48 +- .../crates/std_detect/src/detect/arch/mips.rs | 32 +- .../std_detect/src/detect/arch/mips64.rs | 32 +- .../std_detect/src/detect/arch/powerpc.rs | 45 +- .../std_detect/src/detect/arch/powerpc64.rs | 45 +- .../crates/std_detect/src/detect/arch/x86.rs | 426 +- .../crates/std_detect/src/detect/cache.rs | 132 +- .../crates/std_detect/src/detect/macros.rs | 103 + .../crates/std_detect/src/detect/mod.rs | 63 +- .../std_detect/src/detect/os/aarch64.rs | 19 +- .../src/detect/os/freebsd/aarch64.rs | 9 +- .../std_detect/src/detect/os/freebsd/arm.rs | 12 +- .../src/detect/os/freebsd/auxvec.rs | 36 +- .../std_detect/src/detect/os/freebsd/mod.rs | 2 +- .../src/detect/os/freebsd/powerpc.rs | 12 +- .../std_detect/src/detect/os/linux/aarch64.rs | 29 +- .../std_detect/src/detect/os/linux/arm.rs | 21 +- .../std_detect/src/detect/os/linux/auxvec.rs | 33 +- .../std_detect/src/detect/os/linux/cpuinfo.rs | 5 +- .../std_detect/src/detect/os/linux/mips.rs | 10 +- .../std_detect/src/detect/os/linux/powerpc.rs | 10 +- .../crates/std_detect/src/detect/os/other.rs | 8 +- .../src/detect/os/windows/aarch64.rs | 55 + .../crates/std_detect/src/detect/os/x86.rs | 156 +- src/stdarch/crates/std_detect/src/lib.rs | 9 +- .../crates/std_detect/tests/cpu-detection.rs | 49 +- .../crates/std_detect/tests/x86-specific.rs | 158 + .../crates/stdarch-test/src/disassembly.rs | 139 +- src/stdarch/crates/stdarch-test/src/lib.rs | 3 +- src/stdarch/crates/stdarch-test/src/wasm.rs | 3 +- src/stdarch/crates/stdarch-verify/Cargo.toml | 6 +- src/stdarch/crates/stdarch-verify/src/lib.rs | 46 +- src/test/auxiliary/rust_test_helpers.c | 113 + .../partitioning/extern-drop-glue.rs | 17 +- .../partitioning/local-drop-glue.rs | 39 +- src/test/codegen/cfguard_checks.rs | 10 + src/test/codegen/cfguard_disabled.rs | 10 + src/test/codegen/cfguard_nochecks.rs | 10 + src/test/codegen/enum-discriminant-value.rs | 27 + src/test/codegen/issue-45222.rs | 34 +- src/test/codegen/issue-56927.rs | 2 +- src/test/codegen/naked-functions.rs | 8 +- .../riscv-abi/riscv64-lp64-lp64f-lp64d-abi.rs | 181 + .../codegen/riscv-abi/riscv64-lp64d-abi.rs | 293 + .../riscv-abi/riscv64-lp64f-lp64d-abi.rs | 277 + .../codegen/sanitizer-memory-track-orgins.rs | 8 +- .../codegen/sanitizer-no-sanitize-inlining.rs | 32 + src/test/codegen/sanitizer-no-sanitize.rs | 29 + src/test/codegen/sanitizer-recover.rs | 4 +- .../chalkify/chalk_initial_program.rs | 16 - .../compile-fail/chalkify/generic_impls.rs | 18 - src/test/compile-fail/chalkify/impl_wf.rs | 39 - .../recursive_where_clause_on_type.rs | 28 - src/test/compile-fail/chalkify/type_wf.rs | 24 - src/test/compile-fail/consts/const-err3.rs | 20 - src/test/debuginfo/empty-string.rs | 1 + src/test/debuginfo/generator-locals.rs | 6 +- src/test/debuginfo/generator-objects.rs | 6 +- src/test/debuginfo/issue-12886.rs | 2 +- src/test/debuginfo/issue-57822.rs | 2 +- src/test/debuginfo/no-debug-attribute.rs | 37 - .../incremental/const-generics/issue-68477.rs | 23 + src/test/incremental/crate_hash_reorder.rs | 8 +- .../incremental/cyclic-trait-hierarchy.rs | 2 +- src/test/incremental/issue-38222.rs | 12 +- .../issue-62649-path-collisions-happen.rs | 13 + src/test/incremental/krate-inherent.rs | 8 +- src/test/incremental/krate-inlined.rs | 4 +- .../cgu_invalidated_when_export_added.rs | 26 + .../cgu_invalidated_when_export_removed.rs | 26 + .../cgu_invalidated_when_import_added.rs | 2 +- .../cgu_invalidated_when_import_removed.rs | 2 +- src/test/incremental/warnings-reemitted.rs | 4 +- src/test/mir-opt/const_prop/discriminant.rs | 20 +- src/test/mir-opt/exponential-or.rs | 76 + src/test/mir-opt/generator-drop-cleanup.rs | 8 +- .../mir-opt/generator-storage-dead-unwind.rs | 52 +- src/test/mir-opt/issue-62289.rs | 38 +- src/test/mir-opt/match-arm-scopes.rs | 110 +- src/test/mir-opt/match_false_edges.rs | 118 +- src/test/mir-opt/match_test.rs | 28 +- src/test/mir-opt/remove_fake_borrows.rs | 24 +- src/test/mir-opt/simplify_try.rs | 40 +- src/test/pretty/gat-bounds.rs | 16 + src/test/pretty/if-attr.rs | 37 + .../issue-68710-field-attr-proc-mac-lost.rs | 16 + .../pretty/nested-item-vis-defaultness.rs | 47 + src/test/pretty/trait-inner-attr.rs | 7 + .../run-fail/generator-resume-after-panic.rs | 4 +- src/test/run-fail/mir_indexing_oob_1.rs | 2 +- src/test/run-fail/mir_indexing_oob_2.rs | 2 +- src/test/run-fail/mir_indexing_oob_3.rs | 2 +- src/test/run-fail/overflowing-add.rs | 2 +- src/test/run-fail/overflowing-lsh-1.rs | 2 +- src/test/run-fail/overflowing-lsh-2.rs | 2 +- src/test/run-fail/overflowing-lsh-3.rs | 2 +- src/test/run-fail/overflowing-lsh-4.rs | 2 +- src/test/run-fail/overflowing-mul.rs | 2 +- src/test/run-fail/overflowing-neg.rs | 2 +- src/test/run-fail/overflowing-rsh-1.rs | 2 +- src/test/run-fail/overflowing-rsh-2.rs | 2 +- src/test/run-fail/overflowing-rsh-3.rs | 2 +- src/test/run-fail/overflowing-rsh-4.rs | 2 +- src/test/run-fail/overflowing-rsh-5.rs | 2 +- src/test/run-fail/overflowing-rsh-6.rs | 2 +- src/test/run-fail/overflowing-sub.rs | 2 +- src/test/run-fail/promoted_div_by_zero.rs | 2 +- src/test/run-fail/promoted_overflow.rs | 2 +- .../arguments-non-c-like-enum/Makefile | 7 + .../arguments-non-c-like-enum/nonclike.rs | 31 + .../arguments-non-c-like-enum/test.c | 66 + .../hotplug_codegen_backend/the_backend.rs | 18 +- .../run-make-fulldeps/issue-69368/Makefile | 18 + src/test/run-make-fulldeps/issue-69368/a.rs | 16 + src/test/run-make-fulldeps/issue-69368/b.rs | 8 + src/test/run-make-fulldeps/issue-69368/c.rs | 34 + .../min-global-align/min_global_align.rs | 10 +- .../pass-non-c-like-enum-to-c/Makefile | 5 + .../pass-non-c-like-enum-to-c/nonclike.rs | 21 + .../pass-non-c-like-enum-to-c/test.c | 85 + .../return-non-c-like-enum-from-c/Makefile | 5 + .../return-non-c-like-enum-from-c/nonclike.rs | 31 + .../return-non-c-like-enum-from-c/test.c | 61 + .../return-non-c-like-enum/Makefile | 7 + .../return-non-c-like-enum/nonclike.rs | 21 + .../return-non-c-like-enum/test.c | 63 + .../wasm-stringify-ints-small/Makefile | 2 +- src/test/rustdoc-js/struct-like-variant.js | 7 + src/test/rustdoc-js/struct-like-variant.rs | 8 + .../deny-intra-link-resolution-failure.stderr | 2 +- .../rustdoc-ui/deny-missing-docs-crate.stderr | 2 +- .../rustdoc-ui/deny-missing-docs-macro.stderr | 2 +- src/test/rustdoc-ui/deprecated-attrs.stderr | 4 +- .../rustdoc-ui/doc-without-codeblock.stderr | 2 +- .../rustdoc-ui/intra-doc-alias-ice.stderr | 2 +- .../intra-link-span-ice-55723.stderr | 2 +- .../rustdoc-ui/intra-links-ambiguity.stderr | 2 +- .../rustdoc-ui/intra-links-anchors.stderr | 2 +- .../rustdoc-ui/intra-links-warning.stderr | 1 + src/test/rustdoc-ui/lint-group.stderr | 6 +- .../lint-missing-doc-code-example.stderr | 2 +- .../rustdoc-ui/private-item-doc-test.stderr | 2 +- .../rustdoc/auxiliary/primitive-reexport.rs | 8 + src/test/rustdoc/comment-in-doctest.rs | 2 +- src/test/rustdoc/crate-version-escape.rs | 6 + src/test/rustdoc/doc-spotlight.rs | 36 - .../inline_cross/auxiliary/proc_macro.rs | 13 + src/test/rustdoc/inline_cross/proc_macro.rs | 8 + src/test/rustdoc/primitive-reexport.rs | 28 + src/test/rustdoc/show-const-contents.rs | 6 +- .../auxiliary/issue-40001-plugin.rs | 39 +- .../auxiliary/lint-for-crate-rpass.rs | 18 +- .../ui-fulldeps/auxiliary/lint-for-crate.rs | 19 +- .../auxiliary/lint-group-plugin-test.rs | 24 +- .../ui-fulldeps/auxiliary/lint-plugin-test.rs | 16 +- .../ui-fulldeps/auxiliary/lint-tool-test.rs | 28 +- .../ui-fulldeps/auxiliary/macro-crate-test.rs | 2 +- .../ui-fulldeps/feature-gate-plugin.stderr | 2 +- src/test/ui-fulldeps/gated-plugin.stderr | 2 +- .../hash-stable-is-unstable.stderr | 11 +- .../internal-lints/default_hash_types.stderr | 2 +- .../lint_pass_impl_without_macro.stderr | 3 +- .../internal-lints/pass_ty_by_ref.stderr | 2 +- .../qualified_ty_ty_ctxt.stderr | 2 +- .../internal-lints/ty_tykind_usage.stderr | 2 +- .../lint-group-denied-lint-allowed.rs | 7 + .../ui-fulldeps/lint-plugin-deny-attr.stderr | 2 +- .../lint-plugin-forbid-attrs.stderr | 2 +- src/test/ui-fulldeps/lint-tool-test.stderr | 4 +- .../ui-fulldeps/mod_dir_path_canonicalized.rs | 9 +- .../pathless-extern-unstable.stderr | 2 +- .../ui-fulldeps/plugin-as-extern-crate.rs | 2 +- src/test/ui-fulldeps/pprust-expr-roundtrip.rs | 20 +- src/test/ui/abi/abi-sysv64-arg-passing.rs | 81 + src/test/ui/abi/struct-enums/struct-return.rs | 52 +- src/test/ui/allocator-alloc-one.rs | 18 - src/test/ui/allocator/custom.rs | 6 +- src/test/ui/allocator/not-an-allocator.stderr | 4 + src/test/ui/allocator/two-allocators.stderr | 4 +- src/test/ui/allocator/xcrate-use.rs | 6 +- src/test/ui/anon-params-deprecated.stderr | 2 +- src/test/ui/arg-count-mismatch.rs | 2 +- src/test/ui/arg-count-mismatch.stderr | 6 +- src/test/ui/asm/issue-62046.rs | 11 + src/test/ui/asm/issue-62046.stderr | 11 + src/test/ui/assign-to-method.rs | 22 - src/test/ui/assign-to-method.stderr | 19 - .../associated-const-dead-code.stderr | 2 +- .../associated-const-in-trait.stderr | 6 +- .../associated-const-no-item.stderr | 7 +- ...iated-const-type-parameter-arrays-2.stderr | 8 +- ...ociated-const-type-parameter-arrays.stderr | 8 +- .../associated-const/defaults-cyclic-fail.rs | 17 + .../defaults-cyclic-fail.stderr | 31 + .../associated-const/defaults-cyclic-pass.rs | 36 + .../defaults-not-assumed-fail.rs | 45 + .../defaults-not-assumed-fail.stderr | 31 + .../defaults-not-assumed-pass.rs | 42 + .../associated-item-duplicate-bounds.rs | 11 + .../associated-item-duplicate-bounds.stderr | 11 + .../ui/associated-item/issue-48027.stderr | 6 +- .../bad-bounds-on-assoc-in-trait.rs | 1 - .../bad-bounds-on-assoc-in-trait.stderr | 77 +- .../ui/associated-type-bounds/duplicate.rs | 1 - .../associated-type-bounds/duplicate.stderr | 195 +- .../implied-region-constraints.nll.stderr | 4 +- .../implied-region-constraints.rs | 2 - .../implied-region-constraints.stderr | 4 +- .../ui/associated-type-bounds/inside-adt.rs | 1 - .../associated-type-bounds/inside-adt.stderr | 36 +- ...rojection-from-multiple-supertraits.stderr | 2 +- ...types-invalid-trait-ref-issue-18865.stderr | 8 +- .../associated-types-no-suitable-bound.stderr | 11 +- ...associated-types-overridden-binding.stderr | 8 +- .../associated-types-overridden-default.rs | 11 +- ...associated-types-overridden-default.stderr | 9 - ...ciated-types-project-from-hrtb-in-fn.fixed | 37 + ...ssociated-types-project-from-hrtb-in-fn.rs | 2 + ...iated-types-project-from-hrtb-in-fn.stderr | 4 +- ...iated-types-project-from-hrtb-in-struct.rs | 20 +- ...d-types-project-from-hrtb-in-struct.stderr | 47 +- ...es-project-from-hrtb-in-trait-method.fixed | 38 + ...types-project-from-hrtb-in-trait-method.rs | 15 + ...s-project-from-hrtb-in-trait-method.stderr | 12 +- .../defaults-cyclic-fail-1.rs | 45 + .../defaults-cyclic-fail-1.stderr | 33 + .../defaults-cyclic-fail-2.rs | 47 + .../defaults-cyclic-fail-2.stderr | 33 + .../defaults-cyclic-pass-1.rs | 56 + .../defaults-cyclic-pass-2.rs | 56 + .../defaults-in-other-trait-items-pass.rs | 37 + .../defaults-in-other-trait-items.rs | 50 + .../defaults-in-other-trait-items.stderr | 25 + .../ui/associated-types/defaults-mixed.rs | 34 + .../ui/associated-types/defaults-mixed.stderr | 21 + .../defaults-specialization.rs | 95 + .../defaults-specialization.stderr | 123 + .../associated-types/defaults-suitability.rs | 106 + .../defaults-suitability.stderr | 140 + .../defaults-unsound-62211-1.rs | 63 + .../defaults-unsound-62211-1.stderr | 95 + .../defaults-unsound-62211-2.rs | 63 + .../defaults-unsound-62211-2.stderr | 95 + src/test/ui/associated-types/issue-26681.rs | 20 + .../ui/associated-types/issue-26681.stderr | 14 + src/test/ui/associated-types/issue-32350.rs | 29 + src/test/ui/associated-types/issue-41868.rs | 23 + src/test/ui/associated-types/issue-43924.rs | 15 + .../ui/associated-types/issue-43924.stderr | 23 + src/test/ui/associated-types/issue-47385.rs | 16 + src/test/ui/associated-types/issue-54182-1.rs | 92 + src/test/ui/associated-types/issue-54182-2.rs | 19 + src/test/ui/associated-types/issue-63593.rs | 13 + .../ui/associated-types/issue-63593.stderr | 14 + src/test/ui/associated-types/issue-65774-1.rs | 58 + .../ui/associated-types/issue-65774-1.stderr | 17 + src/test/ui/associated-types/issue-65774-2.rs | 58 + .../ui/associated-types/issue-65774-2.stderr | 17 + src/test/ui/ast-json/ast-json-output.stdout | 2 +- src/test/ui/async-await/async-fn-nonsend.rs | 1 - .../ui/async-await/async-fn-nonsend.stderr | 12 +- src/test/ui/async-await/async-trait-fn.rs | 4 +- src/test/ui/async-await/async-trait-fn.stderr | 12 +- ...015-edition-error-various-positions.stderr | 2 +- .../await-keyword/2015-edition-warning.stderr | 2 +- .../dont-print-desugared-async.stderr | 5 +- .../edition-deny-async-fns-2015.rs | 2 +- .../edition-deny-async-fns-2015.stderr | 42 +- .../async-await/feature-async-closure.stderr | 2 +- .../issue-54239-private-type-triggers-lint.rs | 17 + .../async-await/issues/issue-62097.nll.stderr | 6 +- .../issues/issue-63388-1.nll.stderr | 13 +- .../issues/issue-63388-2.nll.stderr | 2 + .../async-await/issues/issue-63388-2.stderr | 2 + ...65419-generator-resume-after-completion.rs | 6 +- src/test/ui/async-await/no-async-const.rs | 3 +- src/test/ui/async-await/no-async-const.stderr | 6 +- src/test/ui/async-await/no-const-async.rs | 5 +- src/test/ui/async-await/no-const-async.stderr | 19 +- .../no-move-across-await-struct.rs | 1 - .../no-move-across-await-struct.stderr | 2 +- .../async-await/no-move-across-await-tuple.rs | 1 - .../no-move-across-await-tuple.stderr | 2 +- .../no-non-guaranteed-initialization.rs | 1 - .../no-non-guaranteed-initialization.stderr | 2 +- src/test/ui/async-await/no-unsafe-async.rs | 2 +- .../ui/async-await/no-unsafe-async.stderr | 9 +- .../ui/async-await/unreachable-lint-1.stderr | 2 +- .../ui/async-await/unused-lifetime.stderr | 2 +- .../attributes/register-attr-tool-import.rs | 2 + .../register-attr-tool-import.stderr | 12 +- .../register-attr-tool-unused.stderr | 2 +- src/test/ui/auto-ref-slice-plus-ref.stderr | 28 +- src/test/ui/autoderef-full-lval.stderr | 4 - src/test/ui/bad/bad-lint-cap2.stderr | 2 +- src/test/ui/bad/bad-lint-cap3.stderr | 2 +- .../ui/bad/bad-method-typaram-kind.stderr | 7 +- ...her-can-live-while-the-other-survives-2.rs | 15 - ...can-live-while-the-other-survives-2.stderr | 11 - ...her-can-live-while-the-other-survives-3.rs | 18 - ...can-live-while-the-other-survives-3.stderr | 11 - ...her-can-live-while-the-other-survives-4.rs | 15 - ...can-live-while-the-other-survives-4.stderr | 11 - src/test/ui/binop/binop-bitxor-str.stderr | 2 - src/test/ui/binop/binop-consume-args.stderr | 200 +- src/test/ui/binop/binop-move-semantics.stderr | 20 +- src/test/ui/binop/binop-mul-bool.stderr | 2 - src/test/ui/binop/binop-typeck.stderr | 2 - .../ui/blind/blind-item-block-middle.stderr | 9 +- src/test/ui/block-expr-precedence.stderr | 2 +- ...or-patterns-slice-patterns-box-patterns.rs | 224 + ...atterns-slice-patterns-box-patterns.stderr | 208 + ...row-immutable-upvar-mutation-impl-trait.rs | 14 + ...immutable-upvar-mutation-impl-trait.stderr | 16 + .../borrow-immutable-upvar-mutation.rs | 31 +- .../borrow-immutable-upvar-mutation.stderr | 114 +- .../borrow-raw-address-of-mutability.stderr | 32 +- .../borrowck-borrowed-uniq-rvalue-2.stderr | 2 +- .../borrowck-feature-nll-overrides-migrate.rs | 4 +- .../borrowck/borrowck-unboxed-closures.stderr | 10 +- src/test/ui/borrowck/issue-45983.nll.stderr | 2 +- src/test/ui/borrowck/issue-64453.stderr | 4 +- src/test/ui/borrowck/issue-7573.nll.stderr | 2 +- .../ui/borrowck/move-error-snippets.stderr | 22 +- src/test/ui/borrowck/mutability-errors.stderr | 128 +- src/test/ui/borrowck/or-patterns.rs | 64 + src/test/ui/borrowck/or-patterns.stderr | 141 + .../regions-escape-bound-fn-2.nll.stderr | 2 +- .../regions-escape-bound-fn.nll.stderr | 2 +- .../regions-escape-unboxed-closure.nll.stderr | 2 +- .../two-phase-nonrecv-autoref.nll.stderr | 14 +- .../ui/borrowck/two-phase-nonrecv-autoref.rs | 7 - ...ing-interference-future-compat-lint.stderr | 4 +- src/test/ui/bound-suggestions.fixed | 39 + src/test/ui/bound-suggestions.rs | 39 + src/test/ui/bound-suggestions.stderr | 93 + ...builtin-superkinds-double-superkind.stderr | 18 +- .../builtin-superkinds-in-metadata.stderr | 9 +- .../builtin-superkinds-self-type.stderr | 2 +- ...builtin-superkinds-typaram-not-send.stderr | 9 +- src/test/ui/c-variadic/variadic-ffi-1.rs | 4 +- src/test/ui/c-variadic/variadic-ffi-1.stderr | 12 +- src/test/ui/cast-char.stderr | 2 +- src/test/ui/cast/cast-ptr-to-int-const.stderr | 4 +- src/test/ui/chalkify/builtin-copy-clone.rs | 44 - src/test/ui/chalkify/inherent_impl.rs | 42 - src/test/ui/chalkify/lower_env1.rs | 14 - src/test/ui/chalkify/lower_env1.stderr | 22 - src/test/ui/chalkify/lower_env2.rs | 16 - src/test/ui/chalkify/lower_env2.stderr | 23 - src/test/ui/chalkify/lower_env3.rs | 16 - src/test/ui/chalkify/lower_env3.stderr | 20 - src/test/ui/chalkify/lower_impl.rs | 19 - src/test/ui/chalkify/lower_impl.stderr | 18 - src/test/ui/chalkify/lower_struct.rs | 8 - src/test/ui/chalkify/lower_struct.stderr | 13 - src/test/ui/chalkify/lower_trait.rs | 13 - src/test/ui/chalkify/lower_trait.stderr | 24 - .../ui/chalkify/lower_trait_higher_rank.rs | 10 - .../chalkify/lower_trait_higher_rank.stderr | 13 - .../ui/chalkify/lower_trait_where_clause.rs | 17 - .../chalkify/lower_trait_where_clause.stderr | 15 - src/test/ui/chalkify/projection.rs | 25 - src/test/ui/chalkify/super_trait.rs | 19 - src/test/ui/chalkify/trait_implied_bound.rs | 18 - src/test/ui/chalkify/type_implied_bound.rs | 29 - src/test/ui/chalkify/type_inference.rs | 26 - src/test/ui/chalkify/type_inference.stderr | 23 - .../check-static-immutable-mut-slices.stderr | 2 +- ...ds-cant-promote-superkind-in-struct.stderr | 21 +- .../ui/closures/closure-bounds-subtype.stderr | 8 +- .../expect-region-supply-region.nll.stderr | 4 +- .../ui/closures/deeply-nested_closures.rs | 23 + src/test/ui/closures/issue-52437.stderr | 2 +- src/test/ui/closures/issue-67123.stderr | 7 +- .../ui/codemap_tests/bad-format-args.stderr | 2 +- src/test/ui/codemap_tests/issue-28308.stderr | 2 + ...herence-conflicting-negative-trait-impl.rs | 7 +- ...nce-conflicting-negative-trait-impl.stderr | 14 +- ...ce-impl-trait-for-trait-object-safe.stderr | 6 +- src/test/ui/coherence/coherence-impls-send.rs | 4 +- .../ui/coherence/coherence-impls-send.stderr | 23 +- ...erence-inherited-assoc-ty-cycle-err.stderr | 4 +- .../coherence-inherited-subtyping.old.stderr | 14 + .../coherence-inherited-subtyping.re.stderr | 14 + .../coherence-inherited-subtyping.rs | 21 + .../coherence-negative-impls-safe.stderr | 4 +- .../coherence/coherence-subtyping.old.stderr | 14 + .../coherence/coherence-subtyping.re.stderr | 14 + src/test/ui/coherence/coherence-subtyping.rs | 13 +- .../cfg-attr-crate-2.stderr | 2 +- .../cfg-attr-empty-is-unused.stderr | 2 +- .../cfg-attr-multi-invalid-1.stderr | 2 +- .../cfg-attr-multi-invalid-2.stderr | 2 +- .../cfg-attr-multi-true.stderr | 2 +- .../cfg-attr-syntax-validation.stderr | 2 + ...r-unknown-attribute-macro-expansion.stderr | 2 + .../core-traits-no-impls-length-33.rs | 1 - .../core-traits-no-impls-length-33.stderr | 24 +- .../into-iter-no-impls-length-33.stderr | 28 +- .../ui/const-generics/broken-mir-2.stderr | 1 + .../const-arg-type-arg-misordered.rs | 10 + .../const-arg-type-arg-misordered.stderr | 19 + .../const-fn-with-const-param.rs | 2 +- .../const-fn-with-const-param.stderr | 8 +- .../const-param-after-const-literal-arg.rs | 10 + .../const-param-before-other-params.rs | 1 + .../const-param-before-other-params.stderr | 4 +- .../const-param-elided-lifetime.stderr | 1 + .../const-param-in-trait-ungated.stderr | 2 +- ...-type-depends-on-type-param-ungated.stderr | 2 +- .../const-parameter-uppercase-lint.stderr | 2 +- .../derive-debug-array-wrapper.stderr | 1 + .../const-generics/issues/issue-60263.stderr | 2 +- .../ui/const-generics/issues/issue-65675.rs | 10 - .../const-generics/issues/issue-65675.stderr | 8 - src/test/ui/consts/array-literal-index-oob.rs | 4 +- .../ui/consts/array-literal-index-oob.stderr | 18 +- src/test/ui/consts/ascii_ctype.rs | 55 + .../ui/consts/assoc_const_generic_impl.stderr | 2 +- .../ui/consts/const-address-of-mut.stderr | 8 +- src/test/ui/consts/const-deref-ptr.stderr | 2 +- src/test/ui/consts/const-err-early.stderr | 2 +- src/test/ui/consts/const-err-multi.stderr | 2 +- src/test/ui/consts/const-err.rs | 2 +- src/test/ui/consts/const-err.stderr | 2 +- src/test/ui/consts/const-err2.noopt.stderr | 48 + src/test/ui/consts/const-err2.opt.stderr | 48 + ...const-err2.opt_with_overflow_checks.stderr | 48 + src/test/ui/consts/const-err2.rs | 25 +- src/test/ui/consts/const-err2.stderr | 38 - src/test/ui/consts/const-err3.rs | 32 - src/test/ui/consts/const-err3.stderr | 38 - .../conditional_array_execution.stderr | 2 +- .../const-eval/const-eval-overflow2.stderr | 2 +- .../const-eval/const-eval-overflow2b.stderr | 2 +- .../const-eval/const-eval-overflow2c.stderr | 2 +- .../const-eval/const_fn_ptr_fail2.stderr | 4 +- .../ui/consts/const-eval/const_panic.stderr | 6 +- .../const-eval/const_panic_libcore.stderr | 6 +- .../const_panic_libcore_main.stderr | 6 +- src/test/ui/consts/const-eval/dangling.rs | 2 +- src/test/ui/consts/const-eval/dangling.stderr | 2 +- .../feature-gate-const_fn_union.stderr | 2 +- .../feature-gate-const_panic.stderr | 12 +- .../index-out-of-bounds-never-type.stderr | 2 +- .../index_out_of_bounds_propagated.rs | 2 +- .../index_out_of_bounds_propagated.stderr | 6 +- .../ui/consts/const-eval/infinite_loop.stderr | 4 +- .../ui/consts/const-eval/issue-43197.stderr | 2 +- .../ui/consts/const-eval/issue-52442.stderr | 4 +- .../ui/consts/const-eval/issue-52475.stderr | 2 +- .../ui/consts/const-eval/issue-62272.stderr | 4 +- .../ui/consts/const-eval/issue-65394.stderr | 2 +- .../const-eval/match-test-ptr-null.stderr | 4 +- .../const-eval/panic-assoc-never-type.stderr | 4 +- .../consts/const-eval/panic-never-type.stderr | 4 +- .../const-eval/promoted_errors.noopt.stderr | 78 + .../const-eval/promoted_errors.opt.stderr | 72 + ...ted_errors.opt_with_overflow_checks.stderr | 78 + .../ui/consts/const-eval/promoted_errors.rs | 23 +- .../consts/const-eval/promoted_errors.stderr | 60 - .../ui/consts/const-eval/promoted_errors2.rs | 24 - .../consts/const-eval/promoted_errors2.stderr | 66 - .../ui/consts/const-eval/pub_const_err.stderr | 2 +- .../const-eval/pub_const_err_bin.stderr | 2 +- .../consts/const-eval/transmute-const.stderr | 2 +- src/test/ui/consts/const-eval/ub-enum.rs | 83 +- src/test/ui/consts/const-eval/ub-enum.stderr | 82 +- src/test/ui/consts/const-eval/ub-nonnull.rs | 6 +- .../ui/consts/const-eval/ub-nonnull.stderr | 6 +- src/test/ui/consts/const-eval/ub-ref.rs | 15 +- src/test/ui/consts/const-eval/ub-ref.stderr | 46 +- src/test/ui/consts/const-eval/ub-uninhabit.rs | 10 +- .../ui/consts/const-eval/ub-uninhabit.stderr | 10 +- .../ui/consts/const-eval/ub-upvars.stderr | 2 +- src/test/ui/consts/const-eval/ub-wide-ptr.rs | 139 +- .../ui/consts/const-eval/ub-wide-ptr.stderr | 162 +- src/test/ui/consts/const-eval/union-ub.stderr | 2 +- .../validate_uninhabited_zsts.stderr | 4 +- .../const-extern-fn-call-extern-fn.stderr | 4 +- .../const-extern-fn-min-const-fn.stderr | 8 +- .../feature-gate-const_extern_fn.rs | 14 +- .../feature-gate-const_extern_fn.stderr | 48 +- ...const-extern-fns-dont-need-fn-specifier.rs | 1 - ...t-extern-fns-dont-need-fn-specifier.stderr | 12 +- .../const-external-macro-const-err.stderr | 2 +- src/test/ui/consts/const-fn-mismatch.rs | 8 +- src/test/ui/consts/const-fn-mismatch.stderr | 6 +- src/test/ui/consts/const-fn-not-in-trait.rs | 10 +- .../ui/consts/const-fn-not-in-trait.stderr | 10 +- .../consts/const-int-arithmetic-overflow.rs | 26 + src/test/ui/consts/const-int-arithmetic.rs | 147 + src/test/ui/consts/const-int-pow-rpass.rs | 37 + src/test/ui/consts/const-int-unchecked.rs | 22 + src/test/ui/consts/const-int-unchecked.stderr | 138 +- src/test/ui/consts/const-labeled-break.stderr | 2 +- .../ui/consts/const-match-pattern-arm.stderr | 4 +- src/test/ui/consts/const-multi-ref.stderr | 2 +- .../feature-gate-const_mut_refs.stderr | 2 +- src/test/ui/consts/const-nonzero.rs | 11 +- .../ui/consts/const-points-to-static.stderr | 2 +- src/test/ui/consts/const-prop-ice.rs | 2 +- src/test/ui/consts/const-prop-ice.stderr | 6 +- src/test/ui/consts/const-prop-ice2.rs | 2 +- src/test/ui/consts/const-prop-ice2.stderr | 6 +- src/test/ui/consts/const_let_assign3.stderr | 4 +- src/test/ui/consts/const_let_eq.rs | 1 + src/test/ui/consts/const_let_eq_float.rs | 1 + src/test/ui/consts/const_let_refutable.rs | 8 +- src/test/ui/consts/const_let_refutable.stderr | 30 +- .../const_eval_limit_not_reached.rs | 15 + .../const_limit/const_eval_limit_overflow.rs | 15 + .../const_eval_limit_overflow.stderr | 10 + .../const_limit/const_eval_limit_reached.rs | 21 + .../const_eval_limit_reached.stderr | 16 + .../feature-gate-const_eval_limit.rs | 14 + .../feature-gate-const_eval_limit.stderr | 12 + src/test/ui/consts/const_short_circuit.stderr | 4 +- .../ui/consts/control-flow/assert.both.stderr | 2 +- .../control-flow/assert.if_match.stderr | 8 +- .../consts/control-flow/assert.panic.stderr | 6 +- .../consts/control-flow/assert.stock.stderr | 6 +- .../feature-gate-const-if-match.stock.stderr | 48 +- .../control-flow/issue-46843.stock.stderr | 2 +- .../control-flow/issue-50577.if_match.stderr | 2 +- .../control-flow/issue-50577.stock.stderr | 14 +- .../consts/control-flow/loop.if_match.stderr | 26 +- .../ui/consts/control-flow/loop.loop_.stderr | 14 +- .../ui/consts/control-flow/loop.stock.stderr | 30 +- .../control-flow/short-circuit.stock.stderr | 4 +- src/test/ui/consts/enum-discr-type-err.stderr | 2 + src/test/ui/consts/is_ascii.rs | 15 + src/test/ui/consts/issue-63952.rs | 28 + src/test/ui/consts/issue-63952.stderr | 17 + src/test/ui/consts/issue-64059-2.rs | 6 - src/test/ui/consts/issue-64059.rs | 5 + src/test/ui/consts/issue-68684.rs | 15 + src/test/ui/consts/issue-69020.noopt.stderr | 30 + src/test/ui/consts/issue-69020.opt.stderr | 30 + ...ssue-69020.opt_with_overflow_checks.stderr | 30 + src/test/ui/consts/issue-69020.rs | 29 + src/test/ui/consts/issue-69312.rs | 10 + .../ui/consts/min_const_fn/address_of.stderr | 4 +- .../min_const_fn/allow_const_fn_ptr.stderr | 2 +- .../allow_const_fn_ptr_feature_gate.stderr | 1 - .../min_const_fn/bad_const_fn_body_ice.stderr | 4 +- .../ui/consts/min_const_fn/cast_errors.stderr | 10 +- .../min_const_fn/cmp_fn_pointers.stderr | 2 +- .../ui/consts/min_const_fn/loop_ice.stderr | 2 +- .../ui/consts/min_const_fn/min_const_fn.rs | 3 - .../consts/min_const_fn/min_const_fn.stderr | 92 +- .../min_const_fn/min_const_fn_dyn.stderr | 4 +- .../min_const_fn/min_const_fn_fn_ptr.stderr | 4 +- .../min_const_fn/min_const_fn_impl_trait.rs | 9 + .../min_const_fn_impl_trait.stderr | 21 + .../min_const_fn_libstd_stability.stderr | 8 +- .../min_const_fn_unsafe_bad.stderr | 8 +- ...in_const_unsafe_fn_libstd_stability.stderr | 8 +- ...n_const_unsafe_fn_libstd_stability2.stderr | 6 +- .../consts/min_const_fn/mutable_borrow.stderr | 4 +- .../const_refers_to_static.stderr | 6 +- .../miri_unleashed/mutable_const.stderr | 2 +- .../miri_unleashed/mutable_const2.stderr | 2 +- .../consts/miri_unleashed/non_const_fn.stderr | 2 +- .../consts/projection_qualif.mut_refs.stderr | 2 +- .../ui/consts/projection_qualif.stock.stderr | 4 +- ...tatic_mut_containing_mut_ref2.stock.stderr | 2 +- src/test/ui/consts/std/char.rs | 9 - .../ui/consts/too_generic_eval_ice.stderr | 8 +- .../ui/consts/validate_never_arrays.stderr | 6 +- .../cross-crate-macro-backtrace/main.stderr | 2 +- .../ui/cross/cross-file-errors/main.stderr | 2 + .../ui/custom_test_frameworks/mismatch.stderr | 1 + src/test/ui/definition-reachable/nested-fn.rs | 2 +- .../ui/dep-graph/dep-graph-variance-alias.rs | 9 +- .../dep-graph/dep-graph-variance-alias.stderr | 2 +- .../ui/deprecation/deprecation-lint-2.stderr | 4 +- .../ui/deprecation/deprecation-lint-3.stderr | 4 +- .../deprecation-lint-nested.stderr | 2 +- .../ui/deprecation/deprecation-lint.stderr | 2 +- .../rustc_deprecation-in-future.stderr | 2 +- src/test/ui/deprecation/suggestion.stderr | 2 +- src/test/ui/deref-suggestion.stderr | 4 +- .../derives/derive-assoc-type-not-impl.stderr | 11 +- ...ives-span-Clone-enum-struct-variant.stderr | 1 + .../ui/derives/derives-span-Clone-enum.stderr | 1 + .../derives/derives-span-Clone-struct.stderr | 1 + .../derives-span-Clone-tuple-struct.stderr | 1 + ...ives-span-Debug-enum-struct-variant.stderr | 1 + .../ui/derives/derives-span-Debug-enum.stderr | 1 + .../derives/derives-span-Debug-struct.stderr | 1 + .../derives-span-Debug-tuple-struct.stderr | 1 + .../derives-span-Default-struct.stderr | 1 + .../derives-span-Default-tuple-struct.stderr | 1 + ...derives-span-Eq-enum-struct-variant.stderr | 1 + .../ui/derives/derives-span-Eq-enum.stderr | 1 + .../ui/derives/derives-span-Eq-struct.stderr | 1 + .../derives-span-Eq-tuple-struct.stderr | 1 + ...rives-span-Hash-enum-struct-variant.stderr | 2 + .../ui/derives/derives-span-Hash-enum.stderr | 2 + .../derives/derives-span-Hash-struct.stderr | 2 + .../derives-span-Hash-tuple-struct.stderr | 2 + ...erives-span-Ord-enum-struct-variant.stderr | 1 + .../ui/derives/derives-span-Ord-enum.stderr | 1 + .../ui/derives/derives-span-Ord-struct.stderr | 1 + .../derives-span-Ord-tuple-struct.stderr | 1 + ...-span-PartialEq-enum-struct-variant.stderr | 2 + .../derives-span-PartialEq-enum.stderr | 2 + .../derives-span-PartialEq-struct.stderr | 2 + ...derives-span-PartialEq-tuple-struct.stderr | 2 + ...span-PartialOrd-enum-struct-variant.stderr | 5 + .../derives-span-PartialOrd-enum.stderr | 5 + .../derives-span-PartialOrd-struct.stderr | 5 + ...erives-span-PartialOrd-tuple-struct.stderr | 5 + .../deriving-meta-empty-trait-list.stderr | 2 +- ...eriving-no-inner-impl-error-message.stderr | 3 + .../derives/deriving-with-repr-packed.stderr | 6 +- src/test/ui/destructure-trait-ref.stderr | 4 +- .../note-unsupported.stderr | 4 - .../ui/did_you_mean/bad-assoc-expr.stderr | 2 + src/test/ui/did_you_mean/bad-assoc-pat.stderr | 4 + src/test/ui/did_you_mean/bad-assoc-ty.rs | 37 +- src/test/ui/did_you_mean/bad-assoc-ty.stderr | 146 +- src/test/ui/did_you_mean/issue-40006.rs | 20 +- src/test/ui/did_you_mean/issue-40006.stderr | 92 +- .../ui/did_you_mean/recursion_limit.stderr | 2 +- .../did_you_mean/recursion_limit_deref.stderr | 2 +- .../did_you_mean/recursion_limit_macro.stderr | 3 +- ...reference-without-parens-suggestion.stderr | 2 +- .../directory_ownership/macro-expanded-mod.rs | 3 +- .../macro-expanded-mod.stderr | 9 +- .../dollar-crate-is-keyword-2.stderr | 6 + .../dollar-crate-is-keyword.stderr | 8 + src/test/ui/drop/dynamic-drop-async.rs | 10 + src/test/ui/drop/dynamic-drop.rs | 58 +- .../dst/dst-object-from-unsized-type.stderr | 4 +- src/test/ui/duplicate/dupe-symbols-7.rs | 2 +- src/test/ui/duplicate/dupe-symbols-7.stderr | 2 +- src/test/ui/duplicate/dupe-symbols-8.rs | 12 + src/test/ui/duplicate/dupe-symbols-8.stderr | 15 + src/test/ui/duplicate_entry_error.stderr | 2 +- ...dyn-2015-edition-keyword-ident-lint.stderr | 2 +- .../edition-extern-crate-allowed.stderr | 2 +- .../ui/editions/edition-imports-2015.stderr | 2 +- .../ui/editions/edition-imports-2018.stderr | 2 +- .../edition-imports-virtual-2015-gated.stderr | 2 +- ...dition-keywords-2015-2018-expansion.stderr | 2 +- ...dition-keywords-2018-2018-expansion.stderr | 2 +- .../edition-raw-pointer-method-2015.stderr | 2 +- .../elide-errors-on-mismatched-tuple.stderr | 4 +- src/test/ui/empty/empty-never-array.rs | 1 - src/test/ui/empty/empty-never-array.stderr | 11 +- .../ui/enable-unstable-lib-feature.stderr | 2 +- ...re-gate-arbitrary_enum_discriminant.stderr | 6 +- .../ui/enum/enum-discrim-too-small2.stderr | 2 +- src/test/ui/enum/enum-size-variance.stderr | 2 +- src/test/ui/error-codes/E0001.stderr | 2 +- src/test/ui/error-codes/E0009.rs | 9 - src/test/ui/error-codes/E0009.stderr | 11 - src/test/ui/error-codes/E0017.stderr | 8 +- src/test/ui/error-codes/E0033-teach.stderr | 9 +- src/test/ui/error-codes/E0033.stderr | 9 +- src/test/ui/error-codes/E0038.stderr | 10 +- src/test/ui/error-codes/E0055.stderr | 2 +- src/test/ui/error-codes/E0057.stderr | 12 +- src/test/ui/error-codes/E0060.rs | 2 +- src/test/ui/error-codes/E0060.stderr | 6 +- src/test/ui/error-codes/E0061.rs | 4 +- src/test/ui/error-codes/E0061.stderr | 12 +- src/test/ui/error-codes/E0067.stderr | 2 - src/test/ui/error-codes/E0106.stderr | 16 +- src/test/ui/error-codes/E0152.stderr | 2 +- src/test/ui/error-codes/E0184.stderr | 2 + src/test/ui/error-codes/E0197.stderr | 4 +- src/test/ui/error-codes/E0198.stderr | 4 +- src/test/ui/error-codes/E0275.stderr | 6 +- src/test/ui/error-codes/E0388.stderr | 6 +- src/test/ui/error-codes/E0395.stderr | 2 +- src/test/ui/error-codes/E0396.stderr | 2 +- src/test/ui/error-codes/E0637.stderr | 1 + src/test/ui/error-codes/E0658.stderr | 2 +- src/test/ui/error-codes/E0665.stderr | 2 + src/test/ui/error-codes/E0719.stderr | 1 + src/test/ui/error-festival.stderr | 2 - src/test/ui/exclusive-drop-and-copy.stderr | 4 + src/test/ui/explain.stdout | 2 +- src/test/ui/explore-issue-38412.stderr | 14 +- src/test/ui/expr_attr_paren_order.stderr | 2 +- .../ui/extern-flag/public-and-private.stderr | 2 +- src/test/ui/extern/extern-const.stderr | 8 +- src/test/ui/extern/extern-ffi-fn-with-body.rs | 2 +- .../ui/extern/extern-ffi-fn-with-body.stderr | 10 +- .../ui/extern/extern-types-unsized.stderr | 4 +- .../ui/feature-gate-optimize_attribute.stderr | 10 +- .../feature-gate-c_variadic.stderr | 2 +- .../feature-gate-static-nobundle-2.stderr | 2 +- ...issue-43106-gating-of-builtin-attrs.stderr | 4 +- src/test/ui/feature-gate/rustc-private.stderr | 2 +- .../unstable-attribute-allow-issue-0.rs | 6 +- .../unstable-attribute-allow-issue-0.stderr | 18 +- .../feature-gate-abi-msp430-interrupt.stderr | 2 +- .../ui/feature-gates/feature-gate-abi.stderr | 96 +- .../feature-gate-alloc-error-handler.stderr | 2 +- ...-allow-internal-unsafe-nested-macro.stderr | 1 + ...llow-internal-unstable-nested-macro.stderr | 1 + .../feature-gate-allow_fail.stderr | 2 +- .../feature-gate-arbitrary-self-types.stderr | 6 +- ...te-arbitrary_self_types-raw-pointer.stderr | 6 +- .../ui/feature-gates/feature-gate-asm.stderr | 2 +- .../ui/feature-gates/feature-gate-asm2.stderr | 2 +- .../feature-gate-assoc-type-defaults.stderr | 2 +- ...feature-gate-associated_type_bounds.stderr | 26 +- .../feature-gate-box-expr.stderr | 2 +- .../feature-gate-box_patterns.stderr | 2 +- .../feature-gate-box_syntax.stderr | 2 +- .../feature-gate-cfg-target-has-atomic.stderr | 36 +- ...eature-gate-cfg-target-thread-local.stderr | 2 +- .../feature-gate-cfg_sanitize.stderr | 2 +- .../feature-gate-concat_idents.stderr | 4 +- .../feature-gate-concat_idents2.stderr | 4 +- .../feature-gate-concat_idents3.stderr | 4 +- .../ui/feature-gates/feature-gate-const_fn.rs | 6 +- .../feature-gate-const_fn.stderr | 16 +- .../feature-gate-const_generics-ptr.stderr | 8 +- .../feature-gate-const_generics.stderr | 4 +- ...e-const_in_array_repeat_expressions.stderr | 2 +- ...ture-gate-crate_visibility_modifier.stderr | 2 +- ...feature-gate-custom_test_frameworks.stderr | 4 +- .../feature-gate-decl_macro.stderr | 2 +- .../feature-gate-doc_alias.stderr | 2 +- .../feature-gates/feature-gate-doc_cfg.stderr | 2 +- .../feature-gate-doc_keyword.stderr | 2 +- .../feature-gate-doc_masked.stderr | 2 +- .../feature-gate-doc_spotlight.rs | 4 - .../feature-gate-doc_spotlight.stderr | 12 - ...eature-gate-exclusive-range-pattern.stderr | 2 +- .../feature-gate-extern_types.stderr | 2 +- .../feature-gate-external_doc.stderr | 4 +- .../feature-gate-feature-gate.stderr | 2 +- .../feature-gate-ffi_returns_twice.stderr | 2 +- .../feature-gate-fundamental.stderr | 2 +- .../feature-gate-generators.stderr | 6 +- ...ature-gate-generic_associated_types.stderr | 18 +- .../feature-gate-global_asm.stderr | 2 +- ...-infer_static_outlives_requirements.stderr | 2 +- .../feature-gate-is_sorted.stderr | 8 +- .../feature-gate-label_break_value.stderr | 2 +- .../feature-gate-link_args.stderr | 6 +- .../feature-gate-link_cfg.stderr | 2 +- .../feature-gate-link_llvm_intrinsics.stderr | 2 +- .../feature-gates/feature-gate-linkage.stderr | 2 +- .../feature-gate-lint-reasons.stderr | 6 +- .../feature-gate-log_syntax.stderr | 2 +- .../feature-gate-log_syntax2.stderr | 2 +- .../ui/feature-gates/feature-gate-main.stderr | 2 +- .../feature-gate-marker_trait_attr.stderr | 2 +- .../feature-gate-may-dangle.stderr | 2 +- .../feature-gate-member-constraints.rs | 5 +- .../feature-gate-member-constraints.stderr | 10 +- .../feature-gate-min_const_fn.rs | 6 +- .../feature-gate-min_const_fn.stderr | 16 +- .../feature-gate-naked_functions.stderr | 4 +- .../feature-gate-never_type.stderr | 10 +- .../feature-gates/feature-gate-no-debug-2.rs | 5 - .../feature-gate-no-debug-2.stderr | 14 - .../ui/feature-gates/feature-gate-no-debug.rs | 4 - .../feature-gate-no-debug.stderr | 12 - .../feature-gates/feature-gate-no_core.stderr | 2 +- .../feature-gates/feature-gate-no_sanitize.rs | 4 + .../feature-gate-no_sanitize.stderr | 12 + .../feature-gate-non_ascii_idents.stderr | 26 +- ...ature-gate-object_safe_for_dispatch.stderr | 51 +- .../feature-gate-optin-builtin-traits.stderr | 4 +- .../feature-gate-plugin_registrar.stderr | 4 +- .../feature-gate-register_attr.stderr | 2 +- .../feature-gate-register_tool.stderr | 2 +- .../feature-gate-repr-simd.stderr | 4 +- .../feature-gates/feature-gate-repr128.stderr | 2 +- .../feature-gate-rustc-attrs-1.stderr | 3 - .../feature-gate-rustc-attrs.stderr | 4 - .../ui/feature-gates/feature-gate-simd.stderr | 2 +- .../feature-gates/feature-gate-start.stderr | 2 +- .../feature-gate-static-nobundle.stderr | 2 +- .../feature-gate-stmt_expr_attributes.stderr | 2 +- .../feature-gate-thread_local.stderr | 2 +- .../feature-gate-trace_macros.stderr | 2 +- .../feature-gate-track_caller.stderr | 2 +- .../feature-gate-trait-alias.stderr | 2 +- .../feature-gate-transparent_unions.stderr | 2 +- .../feature-gate-try_blocks.stderr | 2 +- .../feature-gate-try_reserve.stderr | 2 +- .../feature-gate-type_alias_impl_trait.stderr | 24 +- .../feature-gate-type_ascription.stderr | 2 +- ...-gate-unboxed-closures-manual-impls.stderr | 14 +- ...-gate-unboxed-closures-method-calls.stderr | 6 +- ...re-gate-unboxed-closures-ufcs-calls.stderr | 6 +- .../feature-gate-unboxed-closures.stderr | 4 +- ...feature-gate-unsized_tuple_coercion.stderr | 2 +- .../feature-gate-untagged_unions.stderr | 6 +- .../feature-gate-unwind-attributes.stderr | 2 +- src/test/ui/fmt/send-sync.stderr | 20 +- src/test/ui/fn/fn-closure-mutable-capture.rs | 4 +- .../ui/fn/fn-closure-mutable-capture.stderr | 13 +- src/test/ui/fn_must_use.stderr | 2 +- src/test/ui/for/for-loop-type-error.stderr | 2 - .../ui/future-incompatible-lint-group.stderr | 2 +- .../generator-yielding-or-returning-itself.rs | 2 +- ...erator-yielding-or-returning-itself.stderr | 27 +- .../async-generator-issue-67158.stderr | 1 + .../generator/auxiliary/xcrate-reachable.rs | 2 +- src/test/ui/generator/auxiliary/xcrate.rs | 4 +- src/test/ui/generator/borrowing.rs | 2 +- src/test/ui/generator/borrowing.stderr | 2 +- src/test/ui/generator/conditional-drop.rs | 8 +- src/test/ui/generator/control-flow.rs | 4 +- src/test/ui/generator/drop-and-replace.rs | 2 +- src/test/ui/generator/drop-env.rs | 4 +- src/test/ui/generator/dropck-resume.rs | 33 + src/test/ui/generator/dropck-resume.stderr | 15 + src/test/ui/generator/dropck.rs | 2 +- .../generator-region-requirements.rs | 2 +- src/test/ui/generator/issue-44197.rs | 13 +- .../issue-61442-stmt-expr-with-drop.rs | 4 +- .../issue-64620-yield-array-element.rs | 9 + .../issue-64620-yield-array-element.stderr | 9 + src/test/ui/generator/issue-69017.rs | 18 + src/test/ui/generator/issue-69039.rs | 30 + src/test/ui/generator/iterator-count.rs | 6 +- .../ui/generator/live-upvar-across-yield.rs | 2 +- src/test/ui/generator/nested_generators.rs | 2 +- .../generator/no-parameters-on-generators.rs | 8 - .../no-parameters-on-generators.stderr | 21 - src/test/ui/generator/not-send-sync.stderr | 2 +- src/test/ui/generator/panic-drops-resume.rs | 37 + src/test/ui/generator/panic-drops.rs | 4 +- src/test/ui/generator/panic-safe.rs | 4 +- .../ref-escapes-but-not-over-yield.stderr | 2 +- src/test/ui/generator/resume-after-return.rs | 4 +- .../ui/generator/resume-arg-late-bound.rs | 17 + .../ui/generator/resume-arg-late-bound.stderr | 15 + .../ui/generator/resume-live-across-yield.rs | 45 + src/test/ui/generator/retain-resume-ref.rs | 25 + .../ui/generator/retain-resume-ref.stderr | 14 + src/test/ui/generator/sized-yield.rs | 2 +- src/test/ui/generator/sized-yield.stderr | 2 +- src/test/ui/generator/smoke-resume-args.rs | 97 + src/test/ui/generator/smoke.rs | 28 +- src/test/ui/generator/static-generators.rs | 4 +- src/test/ui/generator/static-not-unpin.rs | 2 +- src/test/ui/generator/static-not-unpin.stderr | 2 +- src/test/ui/generator/too-many-parameters.rs | 8 + .../ui/generator/too-many-parameters.stderr | 8 + src/test/ui/generator/type-mismatch-error.rs | 22 + .../ui/generator/type-mismatch-error.stderr | 19 + .../type-mismatch-signature-deduction.rs | 6 +- .../type-mismatch-signature-deduction.stderr | 25 +- src/test/ui/generator/xcrate-reachable.rs | 2 +- src/test/ui/generator/xcrate.rs | 6 +- .../ui/generator/yield-while-iterating.rs | 6 +- .../ui/generator/yield-while-iterating.stderr | 2 +- .../generator/yield-while-local-borrowed.rs | 6 +- .../generator/yield-while-ref-reborrowed.rs | 6 +- .../yield-while-ref-reborrowed.stderr | 2 +- .../collections.stderr | 4 +- .../empty_generics.stderr | 5 + .../gat-dont-ice-on-absent-feature-2.stderr | 6 +- .../gat-dont-ice-on-absent-feature.stderr | 2 +- .../generic-associated-types-where.stderr | 6 +- .../impl_bounds.stderr | 8 +- .../issue-47206-where-clause.stderr | 2 +- .../issue-62326-parameter-out-of-range.rs | 2 +- .../issue-62326-parameter-out-of-range.stderr | 15 +- .../issue-67424.stderr | 4 +- .../generic-associated-types/issue-68653.rs | 16 + .../generic-associated-types/iterable.stderr | 26 +- .../parameter_number_and_kind.stderr | 8 +- .../pointer_family.stderr | 2 +- .../ui/generic-associated-types/shadowing.rs | 4 +- .../generic-associated-types/shadowing.stderr | 25 +- .../generic/generic-arg-mismatch-recover.rs | 1 - .../generic-arg-mismatch-recover.stderr | 18 +- .../ui/generic/generic-extern-lifetime.stderr | 12 + src/test/ui/generic/generic-no-mangle.stderr | 2 +- ...rrect-explicit-lifetime-name-needed.stderr | 3 +- ...ature-gate-half-open-range-patterns.stderr | 12 +- ...pats-inclusive-dotdotdot-bad-syntax.stderr | 2 + ...lf-open-range-pats-inclusive-no-end.stderr | 2 + ...pe.bound_a_b_ret_a_vs_bound_a_ret_a.stderr | 1 + .../hr-subtype.bound_a_b_vs_bound_a.stderr | 1 + .../hr-subtype.bound_a_vs_free_x.stderr | 1 + ...-subtype.bound_co_a_b_vs_bound_co_a.stderr | 1 + ...ubtype.bound_co_a_co_b_ret_contra_a.stderr | 1 + ...pe.bound_contra_a_contra_b_ret_co_a.stderr | 1 + ...ubtype.bound_inv_a_b_vs_bound_inv_a.stderr | 1 + ...ubtype.free_inv_x_vs_free_inv_y.nll.stderr | 2 + ...hr-subtype.free_inv_x_vs_free_inv_y.stderr | 2 + .../hr-subtype.free_x_vs_free_y.nll.stderr | 1 + .../hr-subtype.free_x_vs_free_y.stderr | 1 + ...igher-ranker-supertraits-transitive.stderr | 9 +- .../hrtb-higher-ranker-supertraits.stderr | 18 +- src/test/ui/hrtb/issue-58451.rs | 2 +- src/test/ui/hrtb/issue-58451.stderr | 6 +- src/test/ui/huge-array-simple-32.rs | 2 +- src/test/ui/huge-array-simple-64.rs | 2 +- src/test/ui/hygiene/assoc_item_ctxt.stderr | 4 + src/test/ui/hygiene/assoc_ty_bindings.rs | 4 +- .../ui/hygiene/duplicate_lifetimes.stderr | 4 + .../extern-prelude-from-opaque-fail.stderr | 4 + src/test/ui/hygiene/fields-definition.stderr | 6 +- src/test/ui/hygiene/fields-move.stderr | 1 + src/test/ui/hygiene/fields.stderr | 8 + src/test/ui/hygiene/generate-mod.stderr | 8 + src/test/ui/hygiene/globs.stderr | 3 + src/test/ui/hygiene/hygienic-label-1.stderr | 2 + src/test/ui/hygiene/hygienic-label-3.stderr | 2 + .../ui/hygiene/hygienic-labels-in-let.stderr | 32 + src/test/ui/hygiene/hygienic-labels.stderr | 32 + src/test/ui/hygiene/impl_items.stderr | 2 + src/test/ui/hygiene/intercrate.stderr | 2 +- .../ui/hygiene/no_implicit_prelude.stderr | 5 +- src/test/ui/hygiene/privacy-early.stderr | 1 + src/test/ui/hygiene/trait_items.stderr | 1 + src/test/ui/if-attrs/bad-cfg.rs | 5 + src/test/ui/if-attrs/bad-cfg.stderr | 8 + src/test/ui/if-attrs/builtin-if-attr.rs | 12 + src/test/ui/if-attrs/cfg-false-if-attr.rs | 43 + src/test/ui/if-attrs/else-attrs.rs | 25 + src/test/ui/if-attrs/else-attrs.stderr | 27 + src/test/ui/if-attrs/gate-whole-expr.rs | 15 + src/test/ui/if-attrs/let-chains-attr.rs | 13 + src/test/ui/if-attrs/let-chains-attr.stderr | 8 + src/test/ui/if-attrs/stmt-expr-gated.rs | 6 + src/test/ui/if-attrs/stmt-expr-gated.stderr | 12 + src/test/ui/if/if-let.stderr | 3 + src/test/ui/if/ifmt-bad-arg.stderr | 2 + src/test/ui/if/ifmt-bad-format-args.stderr | 2 + src/test/ui/if/ifmt-unimpl.stderr | 1 + src/test/ui/ifmt.rs | 6 - .../assoc-type.stderr | 8 +- src/test/ui/impl-trait/auto-trait-leak.stderr | 150 + .../ui/impl-trait/bound-normalization-fail.rs | 1 - .../bound-normalization-fail.stderr | 8 +- .../ui/impl-trait/equal-hidden-lifetimes.rs | 49 + .../impl-trait/equal-hidden-lifetimes.stderr | 8 + src/test/ui/impl-trait/issue-55872-1.stderr | 15 +- src/test/ui/impl-trait/issue-57200.rs | 15 + src/test/ui/impl-trait/issue-57200.stderr | 8 + src/test/ui/impl-trait/issue-57201.rs | 15 + src/test/ui/impl-trait/issue-57201.stderr | 8 + src/test/ui/impl-trait/issue-60473.rs | 17 + src/test/ui/impl-trait/issue-60473.stderr | 11 + src/test/ui/impl-trait/issue-67166.rs | 11 + src/test/ui/impl-trait/issue-67166.stderr | 11 + ...e-21659-show-relevant-trait-impls-3.stderr | 7 +- .../multiple-lifetimes/error-handling-2.rs | 29 + .../error-handling-2.stderr | 15 + .../multiple-lifetimes/error-handling.rs | 13 +- .../multiple-lifetimes/error-handling.stderr | 17 +- .../ordinary-bounds-unrelated.nll.stderr | 2 + .../ordinary-bounds-unsuited.nll.stderr | 2 + .../must_outlive_least_region_or_bound.rs | 2 +- .../must_outlive_least_region_or_bound.stderr | 2 +- src/test/ui/impl-trait/nested-return-type.rs | 16 + .../no-method-suggested-traits.stderr | 42 +- ...-trait-in-return-position-dyn-trait.stderr | 26 +- .../recursive-impl-trait-type-direct.rs | 5 +- .../recursive-impl-trait-type-direct.stderr | 2 +- .../recursive-impl-trait-type-indirect.rs | 65 +- .../recursive-impl-trait-type-indirect.stderr | 42 +- src/test/ui/impl-trait/trait_type.stderr | 2 +- .../type_parameters_captured.stderr | 2 +- .../ui/impl-trait/unsafety-checking-cycle.rs | 32 + src/test/ui/impl-trait/where-allowed.stderr | 6 +- src/test/ui/imports/extern-crate-used.stderr | 2 +- .../extern-prelude-extern-crate-fail.stderr | 2 + ...e-extern-crate-restricted-shadowing.stderr | 3 + src/test/ui/imports/import-crate-var.stderr | 2 +- .../ui/imports/import-prefix-macro-1.stderr | 2 + .../ui/imports/import-prefix-macro-2.stderr | 2 + .../local-modularized-tricky-fail-1.stderr | 4 + .../local-modularized-tricky-fail-2.stderr | 9 +- .../local-modularized-tricky-fail-3.stderr | 2 + src/test/ui/imports/reexports.stderr | 2 +- .../ui/imports/shadow_builtin_macros.stderr | 1 + .../ui/imports/unresolved-imports-used.stderr | 2 +- src/test/ui/imports/unused-macro-use.stderr | 2 +- src/test/ui/imports/unused.stderr | 2 +- .../in-band-lifetimes/elided-lifetimes.fixed | 2 +- .../ui/in-band-lifetimes/elided-lifetimes.rs | 2 +- .../in-band-lifetimes/elided-lifetimes.stderr | 6 +- ...anon-lifetime-in-struct-declaration.stderr | 4 +- .../no_introducing_in_band_in_locals.stderr | 10 + .../ui/include-macros/mismatched-types.stderr | 2 + .../infer-binary-operand-behind-reference.rs | 30 + .../inference_unstable_forced.stderr | 2 +- .../ui/infinite/infinite-autoderef.stderr | 6 +- .../infinite/infinite-macro-expansion.stderr | 3 +- src/test/ui/inline-asm-bad-constraint.stderr | 6 + .../internal/internal-unstable-const.stderr | 2 +- .../internal/internal-unstable-noallow.stderr | 8 +- src/test/ui/internal/internal-unstable.stderr | 1 + .../ui/invalid-self-argument/bare-fn-start.rs | 6 +- .../bare-fn-start.stderr | 6 +- src/test/ui/invalid-self-argument/bare-fn.rs | 3 +- .../ui/invalid-self-argument/bare-fn.stderr | 4 +- src/test/ui/invalid-self-argument/trait-fn.rs | 2 +- .../ui/invalid-self-argument/trait-fn.stderr | 2 +- src/test/ui/invalid/invalid-no-sanitize.rs | 5 + .../ui/invalid/invalid-no-sanitize.stderr | 10 + .../ui/invalid/invalid-plugin-attr.stderr | 2 +- src/test/ui/issues/auxiliary/issue-51798.rs | 3 + src/test/ui/issues/auxiliary/issue-69725.rs | 8 + src/test/ui/issues/issue-10656.stderr | 2 +- src/test/ui/issues/issue-12116.stderr | 2 +- src/test/ui/issues/issue-12369.stderr | 2 +- src/test/ui/issues/issue-12552.stderr | 3 + src/test/ui/issues/issue-12567.stderr | 4 +- src/test/ui/issues/issue-12997-2.stderr | 2 + src/test/ui/issues/issue-13446.stderr | 2 +- src/test/ui/issues/issue-13727.stderr | 2 +- src/test/ui/issues/issue-14091-2.stderr | 1 + src/test/ui/issues/issue-14221.stderr | 2 +- src/test/ui/issues/issue-14309.stderr | 12 +- src/test/ui/issues/issue-14915.stderr | 2 - src/test/ui/issues/issue-15167.stderr | 8 + src/test/ui/issues/issue-15381.rs | 1 - src/test/ui/issues/issue-15381.stderr | 11 +- src/test/ui/issues/issue-16098.stderr | 3 +- src/test/ui/issues/issue-16250.stderr | 4 +- src/test/ui/issues/issue-16683.nll.stderr | 6 +- src/test/ui/issues/issue-16939.stderr | 6 +- src/test/ui/issues/issue-16966.stderr | 2 +- src/test/ui/issues/issue-17337.stderr | 2 +- src/test/ui/issues/issue-17458.stderr | 2 +- .../issue-17718-const-bad-values.stderr | 4 +- .../ui/issues/issue-17718-const-naming.stderr | 4 +- src/test/ui/issues/issue-17758.nll.stderr | 6 +- src/test/ui/issues/issue-17999.stderr | 2 +- src/test/ui/issues/issue-18294.stderr | 2 +- src/test/ui/issues/issue-18400.stderr | 2 +- src/test/ui/issues/issue-18819.stderr | 6 +- src/test/ui/issues/issue-18919.stderr | 8 +- src/test/ui/issues/issue-18959.stderr | 10 +- src/test/ui/issues/issue-19380.stderr | 9 +- src/test/ui/issues/issue-19538.stderr | 13 +- src/test/ui/issues/issue-19707.stderr | 22 +- src/test/ui/issues/issue-20005.rs | 4 +- src/test/ui/issues/issue-20005.stderr | 17 +- src/test/ui/issues/issue-20313.stderr | 2 +- src/test/ui/issues/issue-20413.rs | 4 +- src/test/ui/issues/issue-20413.stderr | 33 +- src/test/ui/issues/issue-20433.stderr | 4 +- src/test/ui/issues/issue-20692.rs | 2 +- src/test/ui/issues/issue-20692.stderr | 15 +- .../ui/issues/issue-20831-debruijn.stderr | 48 +- src/test/ui/issues/issue-21160.stderr | 2 + src/test/ui/issues/issue-2150.stderr | 3 +- src/test/ui/issues/issue-21596.stderr | 3 +- src/test/ui/issues/issue-21600.stderr | 33 +- src/test/ui/issues/issue-21837.stderr | 10 +- src/test/ui/issues/issue-21974.rs | 4 +- src/test/ui/issues/issue-21974.stderr | 16 +- src/test/ui/issues/issue-22599.stderr | 2 +- src/test/ui/issues/issue-22644.stderr | 2 +- src/test/ui/issues/issue-22777.rs | 2 +- src/test/ui/issues/issue-22933-3.rs | 4 - src/test/ui/issues/issue-22933-3.stderr | 14 - src/test/ui/issues/issue-23024.stderr | 2 +- src/test/ui/issues/issue-23122-2.stderr | 4 +- src/test/ui/issues/issue-23281.stderr | 4 +- src/test/ui/issues/issue-24204.stderr | 4 +- src/test/ui/issues/issue-24363.stderr | 2 - src/test/ui/issues/issue-24424.stderr | 4 +- src/test/ui/issues/issue-25385.stderr | 2 + src/test/ui/issues/issue-25386.stderr | 4 + src/test/ui/issues/issue-25439.stderr | 3 +- src/test/ui/issues/issue-25793.stderr | 2 + src/test/ui/issues/issue-25826.stderr | 2 +- src/test/ui/issues/issue-26056.stderr | 7 +- src/test/ui/issues/issue-26093.stderr | 4 + src/test/ui/issues/issue-26094.rs | 8 +- src/test/ui/issues/issue-26094.stderr | 8 +- src/test/ui/issues/issue-26459.rs | 2 + src/test/ui/issues/issue-26459.stderr | 2 +- src/test/ui/issues/issue-26638.stderr | 6 +- src/test/ui/issues/issue-27060-2.stderr | 2 +- src/test/ui/issues/issue-27060.stderr | 2 +- src/test/ui/issues/issue-27340.stderr | 2 + src/test/ui/issues/issue-27592.stderr | 4 + src/test/ui/issues/issue-27942.stderr | 8 +- src/test/ui/issues/issue-28576.stderr | 9 +- src/test/ui/issues/issue-29084.stderr | 2 + src/test/ui/issues/issue-30240-b.stderr | 2 +- src/test/ui/issues/issue-30255.stderr | 18 +- src/test/ui/issues/issue-30302.stderr | 2 +- src/test/ui/issues/issue-3044.rs | 2 +- src/test/ui/issues/issue-3044.stderr | 10 +- src/test/ui/issues/issue-30730.stderr | 2 +- src/test/ui/issues/issue-31011.stderr | 2 + src/test/ui/issues/issue-31076.stderr | 4 - src/test/ui/issues/issue-31173.rs | 4 + src/test/ui/issues/issue-31173.stderr | 24 +- src/test/ui/issues/issue-31221.stderr | 2 +- src/test/ui/issues/issue-32655.stderr | 2 + src/test/ui/issues/issue-32782.stderr | 1 + src/test/ui/issues/issue-32829.stderr | 4 +- src/test/ui/issues/issue-32950.stderr | 2 + .../issue-33140-traitobject-crate.stderr | 2 +- src/test/ui/issues/issue-3344.stderr | 2 +- src/test/ui/issues/issue-33504.stderr | 9 +- src/test/ui/issues/issue-34229.stderr | 5 + src/test/ui/issues/issue-34255-1.stderr | 2 +- src/test/ui/issues/issue-34334.stderr | 2 +- src/test/ui/issues/issue-34721.stderr | 10 +- src/test/ui/issues/issue-35668.stderr | 2 - src/test/ui/issues/issue-35677.stderr | 4 +- src/test/ui/issues/issue-35976.stderr | 3 + src/test/ui/issues/issue-37026.stderr | 4 +- src/test/ui/issues/issue-37515.stderr | 2 +- src/test/ui/issues/issue-37550.stderr | 2 +- src/test/ui/issues/issue-3763.rs | 3 + src/test/ui/issues/issue-3763.stderr | 10 +- src/test/ui/issues/issue-37887.stderr | 2 +- src/test/ui/issues/issue-38404.stderr | 6 +- src/test/ui/issues/issue-38604.stderr | 13 +- src/test/ui/issues/issue-38821.stderr | 1 + src/test/ui/issues/issue-38940.stderr | 2 +- src/test/ui/issues/issue-38954.stderr | 4 +- src/test/ui/issues/issue-39559.stderr | 4 - src/test/ui/issues/issue-39616.rs | 3 +- src/test/ui/issues/issue-39616.stderr | 4 +- src/test/ui/issues/issue-39848.rs | 3 +- src/test/ui/issues/issue-39848.stderr | 12 +- src/test/ui/issues/issue-40610.stderr | 2 - src/test/ui/issues/issue-41229-ref-str.stderr | 4 +- src/test/ui/issues/issue-41255.stderr | 2 +- src/test/ui/issues/issue-41394.stderr | 2 - src/test/ui/issues/issue-42312.stderr | 12 +- src/test/ui/issues/issue-42954.stderr | 2 + .../issues/issue-43784-associated-type.stderr | 11 +- .../ui/issues/issue-43784-supertrait.stderr | 10 +- src/test/ui/issues/issue-44406.stderr | 2 +- ...45107-unnecessary-unsafe-in-closure.stderr | 2 +- src/test/ui/issues/issue-46576.stderr | 2 +- src/test/ui/issues/issue-46604.stderr | 2 +- src/test/ui/issues/issue-48131.stderr | 2 +- src/test/ui/issues/issue-48364.stderr | 1 + src/test/ui/issues/issue-48728.stderr | 1 + src/test/ui/issues/issue-4935.rs | 2 +- src/test/ui/issues/issue-4935.stderr | 6 +- src/test/ui/issues/issue-4968.stderr | 9 +- src/test/ui/issues/issue-49934.rs | 2 +- src/test/ui/issues/issue-49934.stderr | 2 +- .../option-as_deref.stderr | 3 +- .../option-as_deref_mut.stderr | 3 +- .../result-as_deref.stderr | 3 +- .../result-as_deref_err.stderr | 3 +- .../result-as_deref_mut.stderr | 3 +- .../result-as_deref_mut_err.stderr | 3 +- src/test/ui/issues/issue-50480.stderr | 2 + src/test/ui/issues/issue-50781.stderr | 8 +- src/test/ui/issues/issue-5100.stderr | 11 + src/test/ui/issues/issue-5153.stderr | 7 +- src/test/ui/issues/issue-51714.stderr | 2 +- src/test/ui/issues/issue-51798.rs | 14 + src/test/ui/issues/issue-51848.stderr | 1 + ...issue-52023-array-size-pointer-cast.stderr | 2 +- src/test/ui/issues/issue-53251.stderr | 4 + src/test/ui/issues/issue-53840.rs | 20 - src/test/ui/issues/issue-53840.stderr | 20 - src/test/ui/issues/issue-54348.rs | 4 +- src/test/ui/issues/issue-54348.stderr | 10 +- src/test/ui/issues/issue-54954.rs | 2 +- src/test/ui/issues/issue-54954.stderr | 4 +- src/test/ui/issues/issue-55511.stderr | 2 +- src/test/ui/issues/issue-56411.stderr | 2 + src/test/ui/issues/issue-56685.stderr | 2 +- src/test/ui/issues/issue-57362-1.stderr | 7 +- src/test/ui/issues/issue-57362-2.stderr | 7 +- src/test/ui/issues/issue-57472.stderr | 2 +- src/test/ui/issues/issue-58856-1.stderr | 6 + src/test/ui/issues/issue-58856-2.rs | 2 +- src/test/ui/issues/issue-58856-2.stderr | 12 +- src/test/ui/issues/issue-59488.stderr | 9 +- src/test/ui/issues/issue-59896.stderr | 2 +- src/test/ui/issues/issue-60075.rs | 6 +- src/test/ui/issues/issue-60075.stderr | 22 +- src/test/ui/issues/issue-60622.stderr | 2 +- src/test/ui/issues/issue-6596-1.rs | 2 +- src/test/ui/issues/issue-6596-1.stderr | 6 +- src/test/ui/issues/issue-6596-2.rs | 2 +- src/test/ui/issues/issue-6596-2.stderr | 6 +- src/test/ui/issues/issue-6804.stderr | 2 +- .../issue-68091-unicode-ident-after-if.stderr | 2 + .../issues/issue-68696-catch-during-unwind.rs | 26 + src/test/ui/issues/issue-69306.rs | 45 + src/test/ui/issues/issue-69306.stderr | 115 + .../issue-69396-const-no-type-in-macro.stderr | 5 + ...issue-69602-type-err-during-codegen-ice.rs | 22 + ...e-69602-type-err-during-codegen-ice.stderr | 19 + src/test/ui/issues/issue-69725.rs | 11 + src/test/ui/issues/issue-69725.stderr | 18 + src/test/ui/issues/issue-7246.stderr | 2 +- src/test/ui/issues/issue-7867.stderr | 5 + .../ui/issues/issue-8460-const.noopt.stderr | 150 + .../ui/issues/issue-8460-const.opt.stderr | 150 + ...8460-const.opt_with_overflow_checks.stderr | 150 + src/test/ui/issues/issue-8460-const.rs | 66 +- src/test/ui/issues/issue-8460-const.stderr | 188 - src/test/ui/issues/issue-8460-const2.rs | 50 - src/test/ui/issues/issue-8460-const2.stderr | 128 - src/test/ui/json-short.stderr | 6 +- .../kindck/kindck-impl-type-params.nll.stderr | 32 +- .../ui/kindck/kindck-impl-type-params.stderr | 32 +- .../kindck-inherited-copy-bound.curr.stderr | 13 +- ...copy-bound.object_safe_for_dispatch.stderr | 6 +- .../label/label_break_value_illegal_uses.rs | 2 +- .../label_break_value_illegal_uses.stderr | 4 +- .../homogeneous-aggr-zero-sized-c-struct.rs | 4 +- ...omogeneous-aggr-zero-sized-c-struct.stderr | 4 +- .../homogeneous-aggr-zero-sized-repr-rust.rs | 10 +- ...mogeneous-aggr-zero-sized-repr-rust.stderr | 10 +- src/test/ui/layout/unsafe-cell-hides-niche.rs | 32 + src/test/ui/layout/zero-sized-array-union.rs | 8 +- .../ui/layout/zero-sized-array-union.stderr | 8 +- .../ui/lifetime_starts_expressions.stderr | 2 +- .../lifetimes/borrowck-let-suggestion.stderr | 2 +- .../lifetime-doesnt-live-long-enough.stderr | 80 +- ...urn-type-requires-explicit-lifetime.stderr | 12 +- ...xisting-name-if-else-using-impl.nll.stderr | 2 +- ...isting-name-return-type-is-anon.nll.stderr | 2 +- ...-one-existing-name-self-is-anon.nll.stderr | 2 +- .../ex1b-return-no-names-if-else.stderr | 6 +- ...non-regions-return-type-is-anon.nll.stderr | 2 +- ...-both-anon-regions-self-is-anon.nll.stderr | 2 +- src/test/ui/linkage-attr/linkage4.stderr | 2 +- src/test/ui/lint/dead-code/basic.stderr | 2 +- .../lint/dead-code/empty-unused-enum.stderr | 2 +- src/test/ui/lint/dead-code/impl-trait.stderr | 2 +- .../ui/lint/dead-code/lint-dead-code-1.stderr | 2 +- .../ui/lint/dead-code/lint-dead-code-2.stderr | 2 +- .../ui/lint/dead-code/lint-dead-code-3.stderr | 2 +- .../ui/lint/dead-code/lint-dead-code-4.stderr | 2 +- .../ui/lint/dead-code/lint-dead-code-5.stderr | 2 +- .../ui/lint/dead-code/newline-span.stderr | 2 +- src/test/ui/lint/dead-code/type-alias.stderr | 2 +- src/test/ui/lint/dead-code/unused-enum.stderr | 2 +- .../dead-code/unused-struct-variant.stderr | 2 +- .../ui/lint/dead-code/unused-variant.stderr | 2 +- .../ui/lint/dead-code/with-core-crate.stderr | 2 +- .../inclusive-range-pattern-syntax.stderr | 2 +- .../inline-trait-and-foreign-items.stderr | 6 +- ...0-unused-variable-in-struct-pattern.stderr | 6 +- .../lint/issue-54180-unused-ref-field.stderr | 2 +- .../ui/lint/issue-54538-unused-parens-lint.rs | 1 - .../issue-54538-unused-parens-lint.stderr | 60 +- ...o-snake-case-warning-for-field-puns.stderr | 2 +- .../ui/lint/lint-attr-non-item-node.stderr | 2 +- src/test/ui/lint/lint-change-warnings.stderr | 4 +- src/test/ui/lint/lint-ctypes-enum.stderr | 8 +- src/test/ui/lint/lint-ctypes.stderr | 10 +- ...directives-on-use-items-issue-10534.stderr | 4 +- .../lint-exceeding-bitshifts.noopt.stderr | 146 + .../lint/lint-exceeding-bitshifts.opt.stderr | 146 + ...-bitshifts.opt_with_overflow_checks.stderr | 146 + src/test/ui/lint/lint-exceeding-bitshifts.rs | 71 +- .../ui/lint/lint-exceeding-bitshifts.stderr | 116 - src/test/ui/lint/lint-exceeding-bitshifts2.rs | 20 - .../ui/lint/lint-exceeding-bitshifts2.stderr | 32 - .../lint/lint-forbid-internal-unsafe.stderr | 2 +- .../lint/lint-group-nonstandard-style.stderr | 10 +- src/test/ui/lint/lint-impl-fn.stderr | 6 +- ...lint-lowercase-static-const-pattern.stderr | 2 +- src/test/ui/lint/lint-match-arms.rs | 2 +- src/test/ui/lint/lint-match-arms.stderr | 2 +- src/test/ui/lint/lint-misplaced-attr.stderr | 2 +- .../lint-missing-copy-implementations.stderr | 2 +- src/test/ui/lint/lint-missing-doc.rs | 2 +- src/test/ui/lint/lint-missing-doc.stderr | 2 +- .../ui/lint/lint-non-camel-case-types.stderr | 2 +- .../lint/lint-non-snake-case-crate-2.stderr | 2 +- .../ui/lint/lint-non-snake-case-crate.stderr | 2 +- .../lint/lint-non-snake-case-functions.stderr | 2 +- .../lint/lint-non-snake-case-lifetimes.stderr | 2 +- .../lint/lint-non-snake-case-modules.stderr | 2 +- ...lint-non-uppercase-associated-const.stderr | 2 +- .../ui/lint/lint-non-uppercase-statics.stderr | 2 +- .../ui/lint/lint-owned-heap-memory.stderr | 2 +- src/test/ui/lint/lint-qualification.stderr | 2 +- .../lint/lint-range-endpoint-overflow.stderr | 2 +- src/test/ui/lint/lint-removed-allow.stderr | 2 +- src/test/ui/lint/lint-removed-cmdline.stderr | 2 +- src/test/ui/lint/lint-removed.stderr | 2 +- src/test/ui/lint/lint-renamed-allow.stderr | 2 +- src/test/ui/lint/lint-renamed-cmdline.stderr | 2 +- src/test/ui/lint/lint-renamed.stderr | 2 +- src/test/ui/lint/lint-shorthand-field.stderr | 2 +- .../ui/lint/lint-stability-deprecated.stderr | 2 +- .../lint-stability-fields-deprecated.stderr | 2 +- src/test/ui/lint/lint-stability2.stderr | 4 +- src/test/ui/lint/lint-stability3.stderr | 4 +- src/test/ui/lint/lint-type-limits2.stderr | 2 +- src/test/ui/lint/lint-type-limits3.stderr | 2 +- src/test/ui/lint/lint-type-overflow.stderr | 2 +- src/test/ui/lint/lint-type-overflow2.stderr | 2 +- .../lint/lint-unconditional-recursion.stderr | 2 +- src/test/ui/lint/lint-unknown-lint.stderr | 2 +- .../lint-unnecessary-import-braces.stderr | 2 +- src/test/ui/lint/lint-unnecessary-parens.rs | 3 + .../ui/lint/lint-unnecessary-parens.stderr | 38 +- src/test/ui/lint/lint-unsafe-code.stderr | 4 +- .../ui/lint/lint-unused-extern-crate.stderr | 2 +- src/test/ui/lint/lint-unused-imports.stderr | 2 +- src/test/ui/lint/lint-unused-mut-self.stderr | 2 +- src/test/ui/lint/lint-unused-mut-variables.rs | 52 +- .../ui/lint/lint-unused-mut-variables.stderr | 72 +- src/test/ui/lint/lint-unused-variables.stderr | 2 +- .../ui/lint/lint-uppercase-variables.stderr | 4 +- .../ui/lint/lints-in-foreign-macros.stderr | 5 +- src/test/ui/lint/must-use-ops.stderr | 2 +- src/test/ui/lint/must_use-array.stderr | 2 +- src/test/ui/lint/must_use-trait.stderr | 2 +- src/test/ui/lint/must_use-tuple.stderr | 2 +- src/test/ui/lint/must_use-unit.stderr | 2 +- src/test/ui/lint/opaque-ty-ffi-unsafe.stderr | 2 +- src/test/ui/lint/reasons.rs | 4 +- src/test/ui/lint/reasons.stderr | 4 +- .../redundant-semi-proc-macro.rs | 2 +- .../redundant-semi-proc-macro.stderr | 8 +- .../lint-non-ascii-idents.stderr | 2 +- .../lint-uncommon-codepoints.stderr | 2 +- src/test/ui/lint/suggestions.rs | 4 - src/test/ui/lint/suggestions.stderr | 34 +- src/test/ui/lint/test-inner-fn.stderr | 3 + ...ial-casts-featuring-type-ascription.stderr | 4 +- src/test/ui/lint/trivial-casts.stderr | 4 +- src/test/ui/lint/type-overflow.stderr | 2 +- src/test/ui/lint/uninitialized-zeroed.stderr | 2 +- .../ui/lint/unreachable_pub-pub_crate.stderr | 3 +- src/test/ui/lint/unreachable_pub.stderr | 3 +- .../unused_import_warning_issue_45268.stderr | 2 +- src/test/ui/lint/unused_labels.stderr | 2 +- .../lint/unused_parens_json_suggestion.stderr | 2 +- ...nused_parens_remove_json_suggestion.stderr | 2 +- src/test/ui/lint/use-redundant.stderr | 2 +- ...warn-unused-inline-on-fn-prototypes.stderr | 2 +- src/test/ui/liveness/liveness-dead.stderr | 2 +- .../liveness-return-last-stmt-semi.stderr | 2 + src/test/ui/liveness/liveness-unused.stderr | 6 +- .../main.-Zmacro-backtrace.stderr | 78 + .../ui/macro_backtrace/main.default.stderr | 35 + src/test/ui/macro_backtrace/main.rs | 3 +- src/test/ui/macro_backtrace/main.stderr | 78 - src/test/ui/macros/assert-trailing-junk.rs | 6 +- .../ui/macros/assert-trailing-junk.stderr | 14 +- src/test/ui/macros/assert.stderr | 2 +- src/test/ui/macros/cfg.stderr | 2 + .../derive-in-eager-expansion-hang.stderr | 1 + src/test/ui/macros/format-parse-errors.stderr | 2 +- src/test/ui/macros/issue-54441.rs | 2 +- src/test/ui/macros/issue-54441.stderr | 8 +- .../issue-61053-different-kleene.stderr | 2 +- .../issue-61053-duplicate-binder.stderr | 2 +- .../issue-61053-missing-repetition.stderr | 2 +- src/test/ui/macros/issue-61053-unbound.stderr | 2 +- src/test/ui/macros/issue-68060.rs | 16 + src/test/ui/macros/issue-68060.stderr | 24 + src/test/ui/macros/issue-70446.rs | 13 + .../macro-backtrace-invalid-internals.stderr | 14 + .../ui/macros/macro-backtrace-nested.stderr | 4 + .../ui/macros/macro-backtrace-println.stderr | 2 + src/test/ui/macros/macro-context.stderr | 2 + .../macro-lifetime-used-with-labels.stderr | 2 + .../macros/macro-local-data-key-priv.stderr | 2 +- src/test/ui/macros/macro-shadowing.stderr | 2 + .../ui/macros/macro-use-all-and-none.stderr | 2 +- .../ui/macros/macros-nonfatal-errors.stderr | 6 + .../ui/macros/must-use-in-macro-55516.stderr | 2 +- .../ui/macros/nonterminal-matching.stderr | 2 + .../macros/restricted-shadowing-legacy.stderr | 8 + .../macros/restricted-shadowing-modern.stderr | 6 + src/test/ui/macros/same-sequence-span.stderr | 7 +- .../ui/macros/span-covering-argument-1.stderr | 2 + src/test/ui/macros/trace_faulty_macros.stderr | 5 +- .../malformed/malformed-derive-entry.stderr | 4 + .../malformed/malformed-interpolated.stderr | 4 + .../match/match-arm-resolving-to-never.stderr | 2 - src/test/ui/match/match-ill-type2.stderr | 3 + .../match-no-arms-unreachable-after.stderr | 2 +- src/test/ui/match/match-tag-nullary.stderr | 7 +- src/test/ui/methods/assign-to-method.rs | 24 + src/test/ui/methods/assign-to-method.stderr | 19 + src/test/ui/methods/method-call-err-msg.rs | 8 +- .../ui/methods/method-call-err-msg.stderr | 52 +- ...method-call-lifetime-args-lint-fail.stderr | 2 +- .../method-call-lifetime-args-lint.stderr | 2 +- .../method-on-ambiguous-numeric-type.stderr | 2 - src/test/ui/minus-string.stderr | 2 - .../mir-dataflow/indirect-mutation-offset.rs | 7 + .../indirect-mutation-offset.stderr | 2 +- .../mir-inlining/var-debuginfo-issue-67586.rs | 11 + src/test/ui/mir/mir_assign_eval_order.rs | 2 +- src/test/ui/mir/mir_raw_fat_ptr.rs | 59 +- src/test/ui/mismatched_types/E0409.stderr | 8 +- .../mismatched_types/const-fn-in-trait.stderr | 8 +- .../ui/mismatched_types/issue-26480.stderr | 2 + src/test/ui/mismatched_types/issue-36053-2.rs | 4 + .../ui/mismatched_types/issue-36053-2.stderr | 24 +- .../ui/mismatched_types/issue-38371.stderr | 9 +- .../method-help-unsatisfied-bound.stderr | 5 +- .../mismatched_types/overloaded-calls-bad.rs | 4 +- .../overloaded-calls-bad.stderr | 12 +- src/test/ui/missing/missing-items/m2.stderr | 2 +- .../ui/missing/missing-semicolon-warning.rs | 12 - .../missing/missing-semicolon-warning.stderr | 22 - src/test/ui/missing_debug_impls.rs | 4 +- src/test/ui/missing_debug_impls.stderr | 6 +- src/test/ui/moves/move-out-of-slice-2.rs | 2 +- ...-on-type-no-recursive-stack-closure.stderr | 10 +- src/test/ui/mut/mut-pattern-mismatched.stderr | 6 + .../ui/never_type/defaulted-never-note.stderr | 2 +- .../feature-gate-never_type_fallback.stderr | 1 - src/test/ui/never_type/issue-2149.stderr | 7 +- .../never_type/never-assign-dead-code.stderr | 5 +- src/test/ui/nll/capture-mut-ref.stderr | 2 +- src/test/ui/nll/closure-captures.stderr | 120 +- ...er-to-static-comparing-against-free.stderr | 2 +- src/test/ui/nll/dont-print-desugared.stderr | 5 +- .../nll/issue-54556-used-vs-unused-tails.rs | 2 +- src/test/ui/nll/issue-55850.rs | 2 +- src/test/ui/nll/issue-61424.stderr | 2 +- src/test/ui/nll/outlives-suggestion-simple.rs | 2 +- .../ui/nll/outlives-suggestion-simple.stderr | 8 +- ...ojection-two-region-trait-bound-closure.rs | 4 +- src/test/ui/nll/unused-mut-issue-50343.stderr | 2 +- .../type-annotation-with-hrtb.rs | 33 + src/test/ui/no-patterns-in-args-2.rs | 4 +- src/test/ui/no-patterns-in-args-2.stderr | 8 +- src/test/ui/no-patterns-in-args-macro.rs | 6 +- src/test/ui/no-patterns-in-args-macro.stderr | 4 +- src/test/ui/not-enough-arguments.rs | 2 +- src/test/ui/not-enough-arguments.stderr | 6 +- src/test/ui/object-pointer-types.stderr | 14 +- ...bject-safety-associated-consts.curr.stderr | 10 +- ...ted-consts.object_safe_for_dispatch.stderr | 5 +- .../object-safety-generics.curr.stderr | 20 +- ...y-generics.object_safe_for_dispatch.stderr | 10 +- .../object-safety-issue-22040.stderr | 7 +- .../object-safety-mentions-Self.curr.stderr | 20 +- ...tions-Self.object_safe_for_dispatch.stderr | 10 +- .../object-safety-no-static.curr.stderr | 13 +- ...-no-static.object_safe_for_dispatch.stderr | 8 +- .../object-safety-sized-2.curr.stderr | 11 +- ...ty-sized-2.object_safe_for_dispatch.stderr | 6 +- .../object-safety-sized.curr.stderr | 11 +- ...fety-sized.object_safe_for_dispatch.stderr | 6 +- ...ect-safety-supertrait-mentions-Self.stderr | 7 +- .../feature-gate-on-unimplemented.stderr | 1 - src/test/ui/on-unimplemented/no-debug.stderr | 4 + .../ui/once-cant-call-twice-on-heap.stderr | 10 +- src/test/ui/or-patterns/already-bound-name.rs | 1 - .../ui/or-patterns/already-bound-name.stderr | 46 +- src/test/ui/or-patterns/basic-switch.rs | 33 + src/test/ui/or-patterns/basic-switchint.rs | 54 + src/test/ui/or-patterns/bindings-runpass-1.rs | 25 + src/test/ui/or-patterns/bindings-runpass-2.rs | 32 + src/test/ui/or-patterns/box-patterns.rs | 37 + .../ui/or-patterns/consistent-bindings.rs | 47 +- .../ui/or-patterns/consistent-bindings.stderr | 17 - .../exhaustiveness-non-exhaustive.rs | 12 +- .../exhaustiveness-non-exhaustive.stderr | 14 +- .../ui/or-patterns/exhaustiveness-pass.rs | 18 +- .../ui/or-patterns/exhaustiveness-pass.stderr | 8 - .../exhaustiveness-unreachable-pattern.rs | 27 +- .../exhaustiveness-unreachable-pattern.stderr | 50 +- .../ui/or-patterns/feature-gate-const-fn.rs | 3 +- .../or-patterns/feature-gate-const-fn.stderr | 41 +- ...eature-gate-or_patterns-leading-for.stderr | 2 +- ...eature-gate-or_patterns-leading-let.stderr | 2 +- .../feature-gate-or_patterns.stderr | 38 +- src/test/ui/or-patterns/for-loop.rs | 18 + src/test/ui/or-patterns/if-let-while-let.rs | 22 + src/test/ui/or-patterns/inconsistent-modes.rs | 18 +- .../ui/or-patterns/inconsistent-modes.stderr | 64 +- .../issue-67514-irrefutable-param.rs | 11 + .../issue-68785-irrefutable-param-with-at.rs | 14 + src/test/ui/or-patterns/let-pattern.rs | 19 + src/test/ui/or-patterns/missing-bindings.rs | 2 - .../ui/or-patterns/missing-bindings.stderr | 60 +- src/test/ui/or-patterns/mix-with-wild.rs | 19 + .../ui/or-patterns/multiple-pattern-typo.rs | 1 - .../or-patterns/multiple-pattern-typo.stderr | 22 +- .../ui/or-patterns/or-pattern-mismatch.rs | 4 - .../ui/or-patterns/or-pattern-mismatch.stderr | 9 - .../or-patterns-binding-type-mismatch.rs | 68 + .../or-patterns-binding-type-mismatch.stderr | 257 + .../or-patterns-default-binding-modes.rs | 132 + .../or-patterns/or-patterns-syntactic-fail.rs | 1 - .../or-patterns-syntactic-fail.stderr | 40 +- .../or-patterns/or-patterns-syntactic-pass.rs | 2 +- .../or-patterns-syntactic-pass.stderr | 8 - .../ui/or-patterns/search-via-bindings.rs | 66 + src/test/ui/or-patterns/slice-patterns.rs | 53 + src/test/ui/or-patterns/struct-like.rs | 42 + src/test/ui/out-of-order-shadowing.stderr | 2 +- ...lap-doesnt-conflict-with-specialization.rs | 3 +- src/test/ui/overlap-marker-trait.rs | 31 - src/test/ui/overlap-marker-trait.stderr | 12 - .../panic-handler-duplicate.stderr | 2 +- .../ui/panic-handler/panic-handler-std.stderr | 2 +- src/test/ui/panic-runtime/needs-gate.stderr | 4 +- .../assoc-const-underscore-semantic-fail.rs | 17 + ...ssoc-const-underscore-semantic-fail.stderr | 27 + .../assoc-const-underscore-syntactic-pass.rs | 18 + .../ui/parser/assoc-static-semantic-fail.rs | 51 + .../parser/assoc-static-semantic-fail.stderr | 167 + .../ui/parser/assoc-static-syntactic-fail.rs | 33 + .../parser/assoc-static-syntactic-fail.stderr | 122 + src/test/ui/parser/attr-before-eof.stderr | 4 +- src/test/ui/parser/attr-dangling-in-fn.stderr | 6 +- .../ui/parser/attr-dangling-in-mod.stderr | 4 +- src/test/ui/parser/attr-stmt-expr-attr-bad.rs | 10 +- .../ui/parser/attr-stmt-expr-attr-bad.stderr | 108 +- src/test/ui/parser/attrs-after-extern-mod.rs | 10 +- .../ui/parser/attrs-after-extern-mod.stderr | 8 +- src/test/ui/parser/bounds-lifetime-where.rs | 2 +- .../ui/parser/bounds-lifetime-where.stderr | 4 +- .../ui/parser/default-on-wrong-item-kind.rs | 140 + .../parser/default-on-wrong-item-kind.stderr | 688 ++ src/test/ui/parser/default-unmatched-assoc.rs | 16 + .../ui/parser/default-unmatched-assoc.stderr | 54 + .../ui/parser/default-unmatched-extern.rs | 8 + .../ui/parser/default-unmatched-extern.stderr | 28 + src/test/ui/parser/default-unmatched.rs | 6 + src/test/ui/parser/default-unmatched.stderr | 16 + src/test/ui/parser/default.rs | 4 +- src/test/ui/parser/default.stderr | 19 +- src/test/ui/parser/doc-before-attr.stderr | 6 +- .../ui/parser/doc-before-extern-rbrace.rs | 4 +- .../ui/parser/doc-before-extern-rbrace.stderr | 7 +- src/test/ui/parser/doc-before-semi.rs | 2 - src/test/ui/parser/doc-before-semi.stderr | 8 - src/test/ui/parser/doc-comment-in-stmt.rs | 20 + src/test/ui/parser/doc-comment-in-stmt.stderr | 50 + .../ui/parser/doc-inside-trait-item.stderr | 2 +- src/test/ui/parser/duplicate-visibility.rs | 5 +- .../ui/parser/duplicate-visibility.stderr | 21 +- .../extern-abi-from-mac-literal-frag.rs | 22 +- src/test/ui/parser/extern-crate-async.rs | 12 + .../parser/extern-crate-unexpected-token.rs | 2 +- .../extern-crate-unexpected-token.stderr | 4 +- .../ui/parser/extern-expected-fn-or-brace.rs | 5 +- .../parser/extern-expected-fn-or-brace.stderr | 6 +- src/test/ui/parser/extern-no-fn.rs | 4 +- src/test/ui/parser/extern-no-fn.stderr | 14 +- .../parser/fn-body-optional-semantic-fail.rs | 27 + .../fn-body-optional-semantic-fail.stderr | 40 + .../parser/fn-body-optional-syntactic-pass.rs | 31 + src/test/ui/parser/fn-header-semantic-fail.rs | 58 + .../ui/parser/fn-header-semantic-fail.stderr | 201 + .../ui/parser/fn-header-syntactic-pass.rs | 47 + .../ui/parser/foreign-const-semantic-fail.rs | 9 + .../parser/foreign-const-semantic-fail.stderr | 35 + .../ui/parser/foreign-const-syntactic-fail.rs | 9 + .../foreign-const-syntactic-fail.stderr | 22 + .../ui/parser/foreign-static-semantic-fail.rs | 8 + .../foreign-static-semantic-fail.stderr | 27 + .../parser/foreign-static-syntactic-pass.rs | 11 + .../ui/parser/foreign-ty-semantic-fail.rs | 18 + .../ui/parser/foreign-ty-semantic-fail.stderr | 65 + .../ui/parser/foreign-ty-syntactic-pass.rs | 12 + .../impl-item-type-no-body-semantic-fail.rs | 4 +- ...mpl-item-type-no-body-semantic-fail.stderr | 4 +- src/test/ui/parser/impl-parsing.rs | 3 +- src/test/ui/parser/impl-parsing.stderr | 16 +- .../inner-attr-after-doc-comment.stderr | 2 +- src/test/ui/parser/inner-attr-in-trait-def.rs | 9 + src/test/ui/parser/inner-attr.stderr | 2 +- src/test/ui/parser/inverted-parameters.rs | 1 + src/test/ui/parser/inverted-parameters.stderr | 6 +- src/test/ui/parser/issue-14303-fncall.rs | 2 +- src/test/ui/parser/issue-14303-fncall.stderr | 9 +- src/test/ui/parser/issue-14303-path.rs | 2 +- src/test/ui/parser/issue-14303-path.stderr | 9 +- src/test/ui/parser/issue-17383.stderr | 2 +- src/test/ui/parser/issue-19398.rs | 3 +- src/test/ui/parser/issue-19398.stderr | 9 +- src/test/ui/parser/issue-20711-2.rs | 3 +- src/test/ui/parser/issue-20711-2.stderr | 12 +- src/test/ui/parser/issue-20711.rs | 3 +- src/test/ui/parser/issue-20711.stderr | 11 +- src/test/ui/parser/issue-21153.rs | 3 +- src/test/ui/parser/issue-21153.stderr | 15 +- src/test/ui/parser/issue-24780.rs | 2 +- src/test/ui/parser/issue-24780.stderr | 4 +- src/test/ui/parser/issue-32446.stderr | 7 +- .../parser/issue-35813-postfix-after-cast.rs | 171 + .../issue-35813-postfix-after-cast.stderr | 392 + src/test/ui/parser/issue-41155.rs | 4 +- src/test/ui/parser/issue-41155.stderr | 20 +- ...not-interpolate-impl-items-bad-variants.rs | 44 + ...interpolate-impl-items-bad-variants.stderr | 53 + ...37-macros-cannot-interpolate-impl-items.rs | 34 + ...-58094-missing-right-square-bracket.stderr | 4 +- src/test/ui/parser/issue-62524.stderr | 5 +- src/test/ui/parser/issue-62894.rs | 7 + src/test/ui/parser/issue-62894.stderr | 47 + src/test/ui/parser/issue-63135.rs | 2 +- src/test/ui/parser/issue-63135.stderr | 8 +- ...sue-65122-mac-invoc-in-mut-patterns.stderr | 4 + src/test/ui/parser/issue-6610.stderr | 6 +- src/test/ui/parser/issue-68629.rs | Bin 0 -> 336 bytes src/test/ui/parser/issue-68629.stderr | Bin 0 -> 1441 bytes src/test/ui/parser/issue-68730.rs | Bin 0 -> 170 bytes src/test/ui/parser/issue-68730.stderr | Bin 0 -> 956 bytes .../issue-68788-in-trait-item-propagation.rs | 21 + src/test/ui/parser/issue-68890.rs | 4 + src/test/ui/parser/issue-68890.stderr | 20 + ...sue-70050-ntliteral-accepts-negated-lit.rs | 16 + ...e-70552-ascription-in-parens-after-call.rs | 3 + ...552-ascription-in-parens-after-call.stderr | 8 + .../item-free-const-no-body-semantic-fail.rs | 7 + ...em-free-const-no-body-semantic-fail.stderr | 24 + .../item-free-const-no-body-syntactic-pass.rs | 8 + .../item-free-static-no-body-semantic-fail.rs | 11 + ...m-free-static-no-body-semantic-fail.stderr | 46 + ...item-free-static-no-body-syntactic-pass.rs | 8 + .../item-free-type-bounds-semantic-fail.rs | 20 + ...item-free-type-bounds-semantic-fail.stderr | 67 + .../item-free-type-bounds-syntactic-pass.rs | 13 + src/test/ui/parser/macro/issue-37113.stderr | 2 + src/test/ui/parser/macro/issue-37234.stderr | 2 + .../macro/macro-incomplete-parse.stderr | 2 + src/test/ui/parser/macro/pub-item-macro.rs | 11 +- .../ui/parser/macro/pub-item-macro.stderr | 14 +- .../ui/parser/macro/trait-non-item-macros.rs | 11 +- .../parser/macro/trait-non-item-macros.stderr | 23 +- .../ui/parser/mbe_missing_right_paren.stderr | 8 +- .../missing-close-brace-in-impl-trait.rs | 7 +- .../missing-close-brace-in-impl-trait.stderr | 27 +- .../missing-close-brace-in-trait.rs | 4 +- .../missing-close-brace-in-trait.stderr | 21 +- .../mismatched-delim-brace-empty-block.stderr | 10 +- src/test/ui/parser/missing-semicolon.rs | 8 + src/test/ui/parser/missing-semicolon.stderr | 13 + src/test/ui/parser/missing_right_paren.rs | 2 +- src/test/ui/parser/missing_right_paren.stderr | 8 +- src/test/ui/parser/mut-patterns.rs | 2 + src/test/ui/parser/mut-patterns.stderr | 32 +- .../ui/parser/no-const-fn-in-extern-block.rs | 4 +- .../parser/no-const-fn-in-extern-block.stderr | 21 +- src/test/ui/parser/not-a-pred.stderr | 4 +- .../ui/parser/omitted-arg-in-item-fn.stderr | 4 + src/test/ui/parser/pat-lt-bracket-2.stderr | 4 + src/test/ui/parser/pub-method-macro.rs | 3 +- src/test/ui/parser/pub-method-macro.stderr | 2 +- .../parser/qualified-path-in-turbofish.fixed | 19 + .../ui/parser/qualified-path-in-turbofish.rs | 19 + .../parser/qualified-path-in-turbofish.stderr | 8 + src/test/ui/parser/raw-byte-string-eof.stderr | 3 +- .../ui/parser/raw-str-unterminated.stderr | 3 +- src/test/ui/parser/raw/raw_string.stderr | 3 +- .../ui/parser/recover-from-bad-variant.stderr | 2 +- src/test/ui/parser/recover-range-pats.stderr | 8 +- src/test/ui/parser/recovery-attr-on-if.rs | 9 - src/test/ui/parser/recovery-attr-on-if.stderr | 35 - .../ui/parser/removed-syntax-extern-const.rs | 6 - .../parser/removed-syntax-extern-const.stderr | 8 - .../ui/parser/removed-syntax-static-fn.rs | 4 +- .../ui/parser/removed-syntax-static-fn.stderr | 25 +- .../ui/parser/removed-syntax-with-1.stderr | 5 +- .../ui/parser/self-in-function-arg.stderr | 4 +- .../ui/parser/self-param-semantic-fail.rs | 64 + .../ui/parser/self-param-semantic-fail.stderr | 220 + .../ui/parser/self-param-syntactic-pass.rs | 66 + .../tag-variant-disr-non-nullary.stderr | 2 +- ...item-with-defaultness-fail-semantic.stderr | 24 +- .../parser/type-parameters-in-field-exprs.rs | 6 +- .../type-parameters-in-field-exprs.stderr | 6 +- .../underscore-suffix-for-string.stderr | 2 +- .../ui/parser/underscore_item_not_const.rs | 16 +- .../parser/underscore_item_not_const.stderr | 44 +- src/test/ui/path-lookahead.stderr | 2 +- ...her-can-live-while-the-other-survives-1.rs | 23 +- ...can-live-while-the-other-survives-1.stderr | 59 +- .../bind-by-move-no-subbindings-fun-param.rs | 4 +- ...nd-by-move-no-subbindings-fun-param.stderr | 13 +- .../borrowck-move-and-move.rs | 36 +- .../borrowck-move-and-move.stderr | 69 +- .../borrowck-pat-at-and-box-pass.rs | 11 + .../borrowck-pat-at-and-box.rs | 55 +- .../borrowck-pat-at-and-box.stderr | 151 +- ...k-pat-by-move-and-ref-inverse-promotion.rs | 10 + ...t-by-move-and-ref-inverse-promotion.stderr | 12 + .../borrowck-pat-by-move-and-ref-inverse.rs | 98 + ...orrowck-pat-by-move-and-ref-inverse.stderr | 503 + .../borrowck-pat-by-move-and-ref.rs | 73 +- .../borrowck-pat-by-move-and-ref.stderr | 243 +- .../borrowck-pat-ref-mut-and-ref.rs | 64 +- .../borrowck-pat-ref-mut-and-ref.stderr | 305 +- .../borrowck-pat-ref-mut-twice.rs | 48 +- .../borrowck-pat-ref-mut-twice.stderr | 249 +- .../pattern/bindings-after-at/box-patterns.rs | 36 + .../bindings-after-at/copy-and-move-mixed.rs | 8 +- .../copy-and-move-mixed.stderr | 25 +- ...lt-binding-modes-both-sides-independent.rs | 25 +- ...inding-modes-both-sides-independent.stderr | 74 +- .../feature-gate-bindings_after_at.stderr | 2 +- .../nested-binding-mode-lint.rs | 13 + .../nested-binding-modes-mut.rs | 13 + .../nested-binding-modes-mut.stderr | 21 + .../nested-binding-modes-ref.rs | 13 + .../nested-binding-modes-ref.stderr | 15 + .../or-patterns-box-patterns.rs | 45 + .../or-patterns-slice-patterns.rs | 56 + .../pattern/bindings-after-at/or-patterns.rs | 40 + .../pat-at-same-name-both.rs | 1 - .../pat-at-same-name-both.stderr | 28 +- .../bindings-after-at/slice-patterns.rs | 40 + .../deny-irrefutable-let-patterns.stderr | 2 +- .../borrowck-move-ref-pattern-pass.rs | 31 + .../borrowck-move-ref-pattern.rs | 50 + .../borrowck-move-ref-pattern.stderr | 208 + .../by-move-sub-pat-unreachable.rs | 15 + .../feature-gate-move_ref_pattern.rs | 23 + .../feature-gate-move_ref_pattern.stderr | 66 + .../pattern/move-ref-patterns/issue-53840.rs | 22 + ...ve-ref-patterns-closure-captures-inside.rs | 122 + ...ef-patterns-closure-captures-inside.stderr | 404 + ...move-ref-patterns-closure-captures-pass.rs | 30 + .../move-ref-patterns-closure-captures.rs | 34 + .../move-ref-patterns-closure-captures.stderr | 39 + ...move-ref-patterns-default-binding-modes.rs | 16 + ...-ref-patterns-default-binding-modes.stderr | 21 + .../move-ref-patterns-dynamic-semantics.rs | 81 + src/test/ui/pattern/pat-tuple-bad-type.stderr | 2 + .../ui/pattern/pat-tuple-overfield.stderr | 5 + .../pattern-ident-path-generics.stderr | 2 + src/test/ui/pattern/pattern-tyvar-2.stderr | 2 - .../pattern/rest-pat-semantic-disallowed.rs | 2 +- .../rest-pat-semantic-disallowed.stderr | 1 + .../exhaustive_integer_patterns.stderr | 4 +- .../ui/pattern/usefulness/issue-43253.stderr | 4 +- .../usefulness/match-arm-statics.stderr | 2 +- .../match-byte-array-patterns.stderr | 2 +- .../match-empty-exhaustive_patterns.stderr | 2 +- .../match-range-fail-dominate.stderr | 2 +- .../pattern/usefulness/match-ref-ice.stderr | 2 +- .../pattern/usefulness/match-vec-fixed.stderr | 2 +- .../usefulness/match-vec-unreachable.stderr | 2 +- .../usefulness/slice-pattern-const-2.stderr | 2 +- .../usefulness/slice-pattern-const-3.stderr | 2 +- .../usefulness/slice-pattern-const.stderr | 2 +- .../slice-patterns-reachability.stderr | 2 +- .../struct-pattern-match-useless.stderr | 2 +- .../usefulness/top-level-alternation.stderr | 2 +- src/test/ui/phantom-oibit.stderr | 16 +- .../associated-item-privacy-inherent.stderr | 42 + .../privacy/associated-item-privacy-trait.rs | 9 +- .../associated-item-privacy-trait.stderr | 155 +- .../associated-item-privacy-type-binding.rs | 16 +- ...ssociated-item-privacy-type-binding.stderr | 72 +- .../ui/privacy/private-in-public-assoc-ty.rs | 5 + .../privacy/private-in-public-assoc-ty.stderr | 25 +- .../private-in-public-non-principal.stderr | 2 +- .../ui/privacy/private-in-public-warn.stderr | 2 +- .../ui/privacy/private-inferred-type-3.stderr | 14 +- .../ui/privacy/private-inferred-type.stderr | 12 + .../ui/privacy/pub-priv-dep/pub-priv1.stderr | 2 +- src/test/ui/proc-macro/attr-stmt-expr.stderr | 4 +- .../ui/proc-macro/attributes-included.stderr | 2 +- .../attributes-on-modules-fail.stderr | 8 +- .../auxiliary/generate-dollar-ident.rs | 17 + .../ui/proc-macro/auxiliary/issue-59191.rs | 16 + src/test/ui/proc-macro/derive-bad.stderr | 2 + .../proc-macro/derive-helper-shadowing.stderr | 4 + src/test/ui/proc-macro/dollar-crate.stderr | 3 +- .../ui/proc-macro/expand-to-unstable-2.stderr | 2 +- .../ui/proc-macro/expand-to-unstable.stderr | 1 + .../proc-macro/gen-macro-rules-hygiene.stderr | 4 + .../ui/proc-macro/generate-dollar-ident.rs | 18 + src/test/ui/proc-macro/generate-mod.stderr | 14 +- .../proc-macro/invalid-punct-ident-4.stderr | 7 +- src/test/ui/proc-macro/issue-38586.stderr | 2 + src/test/ui/proc-macro/issue-50493.stderr | 4 + .../issue-59191-replace-root-with-fn.rs | 8 + .../issue-59191-replace-root-with-fn.stderr | 19 + src/test/ui/proc-macro/item-error.stderr | 4 +- .../ui/proc-macro/lints_in_proc_macros.stderr | 7 +- src/test/ui/proc-macro/mixed-site-span.stderr | 15 +- src/test/ui/proc-macro/multispan.stderr | 7 + .../ui/proc-macro/no-macro-use-attr.stderr | 2 +- .../ui/proc-macro/parent-source-spans.stderr | 18 + .../ui/proc-macro/proc-macro-gates.stderr | 26 +- src/test/ui/proc-macro/subspan.stderr | 24 +- src/test/ui/proc-macro/three-equals.stderr | 1 + src/test/ui/proc-macro/trait-fn-args-2015.rs | 14 + src/test/ui/pub/pub-restricted-error-fn.rs | 5 +- .../ui/pub/pub-restricted-error-fn.stderr | 16 +- .../range-inclusive-pattern-precedence.stderr | 2 +- src/test/ui/range/range_traits-1.stderr | 36 + src/test/ui/range/range_traits-2.stderr | 2 + src/test/ui/range/range_traits-3.stderr | 2 + src/test/ui/range/range_traits-6.stderr | 2 + .../ui/raw-ref-op/feature-raw-ref-op.stderr | 12 +- src/test/ui/reachable/expr_add.stderr | 2 +- src/test/ui/reachable/expr_again.stderr | 4 +- src/test/ui/reachable/expr_array.stderr | 2 +- src/test/ui/reachable/expr_assign.stderr | 2 +- src/test/ui/reachable/expr_block.stderr | 4 +- src/test/ui/reachable/expr_box.stderr | 2 +- src/test/ui/reachable/expr_call.stderr | 2 +- src/test/ui/reachable/expr_cast.stderr | 2 +- src/test/ui/reachable/expr_if.stderr | 4 +- src/test/ui/reachable/expr_loop.stderr | 8 +- src/test/ui/reachable/expr_match.stderr | 6 +- src/test/ui/reachable/expr_method.stderr | 2 +- src/test/ui/reachable/expr_repeat.stderr | 2 +- src/test/ui/reachable/expr_return.stderr | 2 +- .../ui/reachable/expr_return_in_macro.stderr | 2 +- src/test/ui/reachable/expr_struct.stderr | 2 +- src/test/ui/reachable/expr_tup.stderr | 2 +- src/test/ui/reachable/expr_type.stderr | 2 +- src/test/ui/reachable/expr_unary.stderr | 2 +- src/test/ui/reachable/expr_while.stderr | 2 +- src/test/ui/reachable/unreachable-arm.stderr | 2 +- src/test/ui/reachable/unreachable-code.stderr | 2 +- .../ui/reachable/unreachable-in-call.stderr | 2 +- .../unreachable-loop-patterns.stderr | 2 +- .../reachable/unreachable-try-pattern.stderr | 4 +- .../reachable/unwarned-match-on-never.stderr | 2 +- src/test/ui/realloc-16687.rs | 14 +- src/test/ui/recursion/recursion.rs | 1 + src/test/ui/recursion/recursion.stderr | 2 +- .../recursive-types-are-not-uninhabited.rs | 1 - ...recursive-types-are-not-uninhabited.stderr | 11 +- src/test/ui/recursion_limit/empty.rs | 6 + src/test/ui/recursion_limit/empty.stderr | 10 + src/test/ui/recursion_limit/invalid_digit.rs | 6 + .../ui/recursion_limit/invalid_digit.stderr | 10 + src/test/ui/recursion_limit/overflow.rs | 7 + src/test/ui/recursion_limit/overflow.stderr | 10 + src/test/ui/recursion_limit/zero.rs | 12 + src/test/ui/recursion_limit/zero.stderr | 10 + ...hod-type-parameters-trait-bound.nll.stderr | 2 +- .../regions-close-object-into-object-5.stderr | 14 +- ...regions-close-over-type-parameter-1.stderr | 8 +- .../regions-close-param-into-object.stderr | 8 +- .../ui/regions/regions-enum-not-wf.stderr | 8 +- ...gions-free-region-ordering-callee-4.stderr | 10 +- ...ons-implied-bounds-projection-gap-1.stderr | 2 +- ...-implied-bounds-projection-gap-hr-1.stderr | 9 +- .../ui/regions/regions-in-enums-anon.stderr | 4 +- .../ui/regions/regions-in-structs-anon.stderr | 4 +- .../regions-infer-bound-from-trait.stderr | 4 +- src/test/ui/regions/regions-mock-codegen.rs | 16 +- .../ui/regions/regions-name-undeclared.stderr | 20 + .../ui/regions/regions-nested-fns.nll.stderr | 2 +- ...ions-normalize-in-where-clause-list.stderr | 22 +- src/test/ui/regions/regions-trait-object-1.rs | 4 +- .../regions-var-type-out-of-scope.stderr | 1 - src/test/ui/removing-extern-crate.stderr | 2 +- src/test/ui/repr/feature-gate-no-niche.rs | 20 + src/test/ui/repr/feature-gate-no-niche.stderr | 35 + .../repr-no-niche-inapplicable-to-unions.rs | 14 + ...epr-no-niche-inapplicable-to-unions.stderr | 19 + src/test/ui/repr/repr-no-niche.rs | 329 + .../ui/reserved/reserved-attr-on-macro.stderr | 1 - src/test/ui/resolve/issue-3907-2.stderr | 6 +- .../issue-69401-trait-fn-no-body-ty-local.rs | 6 + ...sue-69401-trait-fn-no-body-ty-local.stderr | 9 + src/test/ui/resolve/name-clash-nullary.stderr | 4 +- .../resolve-inconsistent-binding-mode.rs | 33 +- .../resolve-inconsistent-binding-mode.stderr | 61 +- .../ui/resolve/resolve-inconsistent-names.rs | 2 +- .../resolve/resolve-inconsistent-names.stderr | 8 +- .../ui/resolve/resolve-primitive-fallback.rs | 2 +- .../resolve/resolve-primitive-fallback.stderr | 11 +- .../typo-suggestion-named-underscore.rs | 14 + .../typo-suggestion-named-underscore.stderr | 16 + .../ui/return/return-match-array-const.stderr | 6 +- .../termination-trait-test-wrong-type.stderr | 1 + .../const.stderr | 11 +- .../ui/rfc-2005-default-binding-mode/for.rs | 7 +- .../rfc-2005-default-binding-mode/for.stderr | 15 +- .../issue-44912-or.rs | 2 +- .../issue-44912-or.stderr | 2 +- .../rfc-2005-default-binding-mode/lit.stderr | 4 + .../extern_crate_improper.stderr | 2 +- .../issue-65157-repeated-match-arm.stderr | 2 +- .../uninhabited/patterns_same_crate.stderr | 2 +- .../caller-location-fnptr-rt-ctfe-equiv.rs | 32 + ...caller-location-fnptr-rt-ctfe-equiv.stderr | 6 + .../dont-infer-static.stderr | 2 +- .../regions-enum-not-wf.stderr | 8 +- .../regions-struct-not-wf.stderr | 4 +- .../dbg-macro-move-semantics.stderr | 2 - .../dbg-macro-requires-debug.stderr | 2 +- .../disallowed-positions.stderr | 12 +- .../feature-gate.stderr | 64 +- .../param-attrs-cfg.stderr | 2 +- .../feature-gate-raw-dylib-2.stderr | 2 +- .../feature-gate-raw-dylib.stderr | 2 +- .../rfc-2632-const-trait-impl/assoc-type.rs | 28 + .../call-const-trait-method-fail.rs | 30 + .../call-const-trait-method-fail.stderr | 9 + .../call-const-trait-method-pass.rs | 41 + .../const-and-non-const-impl.rs | 33 + .../const-and-non-const-impl.stderr | 34 + .../const-check-fns-in-const-impl.rs | 16 + .../const-check-fns-in-const-impl.stderr | 12 + .../feature-gate.stock.stderr | 2 +- .../feature-gate.gated.stderr | 8 +- .../rfc-2632-const-trait-impl/feature-gate.rs | 5 +- .../feature-gate.stock.stderr | 12 +- .../generic-bound.rs | 32 + .../inherent-impl.rs | 2 - .../inherent-impl.stderr | 24 +- .../ui/rfc-2632-const-trait-impl/stability.rs | 43 + .../stability.stderr | 24 + ...ide-behind-doubly-indirect-embedded.stderr | 2 +- ...t-hide-behind-doubly-indirect-param.stderr | 2 +- ...ide-behind-indirect-struct-embedded.stderr | 2 +- ...t-hide-behind-indirect-struct-param.stderr | 2 +- .../ui/rfc1445/feature-gate.no_gate.stderr | 4 +- ...-match-ref-ref-forbidden-without-eq.stderr | 2 +- src/test/ui/rfc1623-2.rs | 13 + src/test/ui/rfc1623-2.stderr | 29 + src/test/ui/rfc1623.rs | 13 +- src/test/ui/rfc1623.stderr | 51 +- .../ui/rust-2018/async-ident-allowed.stderr | 2 +- src/test/ui/rust-2018/async-ident.stderr | 2 +- src/test/ui/rust-2018/dyn-keyword.stderr | 2 +- .../edition-lint-fully-qualified-paths.stderr | 2 +- ...ition-lint-infer-outlives-multispan.stderr | 2 +- .../edition-lint-infer-outlives.stderr | 2 +- .../edition-lint-nested-empty-paths.stderr | 2 +- .../edition-lint-nested-paths.stderr | 2 +- .../ui/rust-2018/edition-lint-paths.stderr | 2 +- .../extern-crate-idiomatic-in-2018.stderr | 2 +- .../ui/rust-2018/extern-crate-rename.stderr | 2 +- .../ui/rust-2018/extern-crate-submod.stderr | 2 +- ...54400-unused-extern-crate-attr-span.stderr | 2 +- .../ui/rust-2018/macro-use-warned-against.rs | 2 +- .../rust-2018/macro-use-warned-against.stderr | 6 +- .../ui/rust-2018/remove-extern-crate.stderr | 2 +- .../suggestions-not-always-applicable.stderr | 4 +- src/test/ui/rust-2018/try-ident.stderr | 2 +- src/test/ui/rust-2018/try-macro.stderr | 2 +- .../ambiguity-macros-nested.stderr | 1 + .../uniform-paths/ambiguity-macros.stderr | 1 + src/test/ui/sanitize-inline-always.rs | 15 + src/test/ui/sanitize-inline-always.stderr | 13 + src/test/ui/sanitize/address.rs | 20 + src/test/ui/sanitize/badfree.rs | 19 + .../ui/{sanitize-cfg.rs => sanitize/cfg.rs} | 0 .../{sanitizer-leak.rs => sanitize/leak.rs} | 0 .../memory.rs} | 0 .../new-llvm-pass-manager-thin-lto.rs | 27 + .../unsupported-target.rs} | 0 .../unsupported-target.stderr} | 0 src/test/ui/sanitize/use-after-scope.rs | 18 + src/test/ui/sanitizer-address.rs | 21 - src/test/ui/save-analysis/issue-68621.rs | 17 + src/test/ui/save-analysis/issue-68621.stderr | 8 + ...ary-self-types-not-object-safe.curr.stderr | 14 +- ...bject-safe.object_safe_for_dispatch.stderr | 7 +- ...f_types_pin_lifetime_impl_trait.nll.stderr | 2 +- ...rary_self_types_pin_lifetime_impl_trait.rs | 2 - ..._self_types_pin_lifetime_impl_trait.stderr | 8 +- ...pes_pin_lifetime_mismatch-async.nll.stderr | 25 +- ...elf_types_pin_lifetime_mismatch.nll.stderr | 12 +- ...itrary_self_types_pin_lifetime_mismatch.rs | 2 - ...ry_self_types_pin_lifetime_mismatch.stderr | 6 +- .../self/elision/lt-ref-self-async.nll.stderr | 63 +- .../ui/self/elision/lt-ref-self.nll.stderr | 12 +- .../elision/ref-mut-self-async.nll.stderr | 63 +- .../ui/self/elision/ref-mut-self.nll.stderr | 12 +- .../elision/ref-mut-struct-async.nll.stderr | 53 +- .../ui/self/elision/ref-mut-struct.nll.stderr | 10 +- .../ui/self/elision/ref-self-async.nll.stderr | 2 +- src/test/ui/self/elision/ref-self.nll.stderr | 14 +- .../self/elision/ref-struct-async.nll.stderr | 53 +- .../ui/self/elision/ref-struct.nll.stderr | 10 +- ...at-arbitrary-self-type-trait-method.stderr | 8 +- src/test/ui/self/self-infer.rs | 2 - src/test/ui/self/self-infer.stderr | 16 +- src/test/ui/shadow-bool.rs | 18 + .../ui/single-use-lifetime/fn-types.stderr | 2 +- .../one-use-in-fn-argument-in-band.stderr | 2 +- .../one-use-in-fn-argument.stderr | 2 +- .../one-use-in-inherent-impl-header.stderr | 2 +- ...one-use-in-inherent-method-argument.stderr | 2 +- .../one-use-in-inherent-method-return.stderr | 2 +- .../one-use-in-trait-method-argument.stderr | 2 +- ...inherent-method-argument-and-return.stderr | 2 +- .../zero-uses-in-fn.stderr | 2 +- .../zero-uses-in-impl.stderr | 2 +- ...ghtly-nice-generic-literal-messages.stderr | 2 + src/test/ui/span/E0057.stderr | 12 +- src/test/ui/span/E0204.stderr | 4 + src/test/ui/span/coerce-suggestions.stderr | 2 +- .../ui/span/gated-features-attr-spans.stderr | 2 +- .../ui/span/impl-wrong-item-for-trait.stderr | 2 +- src/test/ui/span/issue-24690.stderr | 2 +- src/test/ui/span/issue-33884.stderr | 2 +- src/test/ui/span/issue-34264.stderr | 20 +- src/test/ui/span/issue-36530.stderr | 2 +- src/test/ui/span/issue-39018.stderr | 4 - src/test/ui/span/issue-7575.stderr | 13 +- src/test/ui/span/lint-unused-unsafe.stderr | 2 +- .../ui/span/macro-span-replacement.stderr | 3 +- src/test/ui/span/missing-unit-argument.stderr | 28 +- src/test/ui/span/multispan-import-lint.stderr | 2 +- src/test/ui/span/slice-borrow.stderr | 2 +- .../unused-warning-point-at-identifier.stderr | 2 +- ...specialization-feature-gate-default.stderr | 2 +- ...pecialization-trait-not-implemented.stderr | 14 +- .../defaultimpl/specialization-wfcheck.stderr | 10 +- .../specialization/defaultimpl/validation.rs | 2 +- .../defaultimpl/validation.stderr | 8 +- src/test/ui/specialization/issue-39618.rs | 27 + .../soundness/partial_eq_range_inclusive.rs | 35 + .../soundness/partial_ord_slice.rs | 42 + ...specialization-feature-gate-default.stderr | 2 +- .../stability-attribute-issue.stderr | 4 +- .../stability-attribute-sanity-2.rs | 3 +- .../stability-attribute-sanity-2.stderr | 8 +- src/test/ui/stable-features.stderr | 2 +- src/test/ui/std-backtrace.rs | 4 +- src/test/ui/stmt_expr_attrs_no_feature.stderr | 18 +- src/test/ui/str/str-mut-idx.stderr | 4 +- .../ui/suggestions/attribute-typos.stderr | 1 - .../ui/suggestions/const-in-struct-pat.rs | 11 + .../ui/suggestions/const-in-struct-pat.stderr | 16 + ...gest-deref-inside-macro-issue-58298.stderr | 7 +- .../duplicate-suggestions.stderr | 30 +- .../dont-suggest-ref/simple.stderr | 51 +- .../dont-suggest-try_into-in-macros.stderr | 2 +- .../expected-boxed-future-isnt-pinned.rs | 29 + .../expected-boxed-future-isnt-pinned.stderr | 20 + .../fn-missing-lifetime-in-item.rs | 8 + .../fn-missing-lifetime-in-item.stderr | 49 + .../ui/suggestions/imm-ref-trait-object.rs | 5 + .../suggestions/imm-ref-trait-object.stderr | 7 +- .../impl-trait-missing-lifetime.rs | 2 + .../impl-trait-missing-lifetime.stderr | 14 + src/test/ui/suggestions/issue-61963.stderr | 2 +- .../suggestions/issue-64252-self-type.stderr | 4 + .../ui/suggestions/match-ergonomics.stderr | 6 +- .../suggestions/method-missing-parentheses.rs | 5 + .../method-missing-parentheses.stderr | 17 + ...sing-assoc-fn-applicable-suggestions.fixed | 21 + ...missing-assoc-fn-applicable-suggestions.rs | 18 + ...ing-assoc-fn-applicable-suggestions.stderr | 16 + src/test/ui/suggestions/missing-assoc-fn.rs | 22 + .../ui/suggestions/missing-assoc-fn.stderr | 36 + ...issing-assoc-type-bound-restriction.stderr | 21 +- .../missing-trait-bounds-for-method-call.rs | 31 + ...issing-trait-bounds-for-method-call.stderr | 39 + .../ui/suggestions/missing-trait-item.fixed | 8 +- .../suggestions/mut-borrow-needed-by-trait.rs | 4 + .../mut-borrow-needed-by-trait.stderr | 18 +- .../object-unsafe-trait-references-self.rs | 12 + ...object-unsafe-trait-references-self.stderr | 30 + .../object-unsafe-trait-should-use-self.rs | 16 + ...object-unsafe-trait-should-use-self.stderr | 54 + ...-unsafe-trait-should-use-where-sized.fixed | 13 + ...ect-unsafe-trait-should-use-where-sized.rs | 13 + ...unsafe-trait-should-use-where-sized.stderr | 35 + src/test/ui/suggestions/path-display.stderr | 1 + .../suggestions/restrict-type-argument.stderr | 54 +- .../return-without-lifetime.stderr | 4 +- .../suggestions/struct-initializer-comma.rs | 13 + .../struct-initializer-comma.stderr | 23 + .../suggest-impl-trait-lifetime.fixed | 2 +- .../suggest-impl-trait-lifetime.rs | 2 +- .../suggest-impl-trait-lifetime.stderr | 7 +- src/test/ui/suggestions/suggest-move-types.rs | 8 +- .../ui/suggestions/suggest-move-types.stderr | 29 +- .../suggestions/suggest-remove-refs-1.stderr | 2 +- .../ui/suggestions/suggest-split-at-mut.rs | 8 + .../suggestions/suggest-split-at-mut.stderr | 15 + .../type-ascription-instead-of-method.stderr | 2 +- .../type-ascription-instead-of-path-2.stderr | 2 +- .../type-ascription-instead-of-variant.stderr | 2 +- .../unused-closure-argument.stderr | 2 +- .../suggestions/vec-macro-in-pattern.stderr | 2 +- src/test/ui/super-fast-paren-parsing.rs | 1 + src/test/ui/suppressed-error.stderr | 4 +- .../syntax-trait-polarity-feature-gate.stderr | 2 +- src/test/ui/syntax-trait-polarity.stderr | 8 +- src/test/ui/target-feature/gate.stderr | 2 +- .../ui/test-attrs/test-warns-dead-code.stderr | 2 +- src/test/ui/test-panic-abort-nocapture.rs | 39 + .../ui/test-panic-abort-nocapture.run.stderr | 9 + .../ui/test-panic-abort-nocapture.run.stdout | 23 + .../ui/tool-attributes/diagnostic_item.stderr | 1 - src/test/ui/tool_lints-fail.stderr | 2 +- src/test/ui/trace_macros-gate.stderr | 9 +- ...overlap-not-permitted-for-builtin-trait.rs | 11 + ...lap-not-permitted-for-builtin-trait.stderr | 11 + ...overlap-permitted-for-marker-traits-neg.rs | 12 - .../overlap-permitted-for-marker-traits.rs | 27 - .../reservation-impl-coherence-conflict.rs | 2 - ...reservation-impl-coherence-conflict.stderr | 2 +- .../reservation-impl-no-use.rs | 2 - .../reservation-impl-no-use.stderr | 2 +- .../trait-alias/trait-alias-object-fail.rs | 5 + .../trait-alias-object-fail.stderr | 9 +- .../traits/trait-alias/trait-alias-wf.stderr | 13 +- ...-bounds-on-structs-and-enums-in-fns.stderr | 8 +- ...rait-bounds-on-structs-and-enums-xc.stderr | 8 +- .../trait-bounds-on-structs-and-enums.stderr | 26 +- src/test/ui/traits/trait-item-privacy.stderr | 33 +- .../traits/trait-object-macro-matcher.stderr | 2 +- src/test/ui/traits/trait-object-safety.stderr | 17 +- .../ui/traits/trait-object-vs-lifetime.rs | 2 +- .../ui/traits/trait-object-vs-lifetime.stderr | 17 +- .../trait-resolution-in-overloaded-op.stderr | 2 - .../traits/trait-safety-inherent-impl.stderr | 6 +- .../traits/trait-suggest-where-clause.stderr | 4 +- src/test/ui/traits/trait-test-2.stderr | 19 +- .../traits-repeated-supertrait-ambig.stderr | 16 +- .../ui/traits/wf-trait-object-maybe-bound.rs | 2 - .../traits/wf-trait-object-maybe-bound.stderr | 10 +- .../trivial-bounds/trivial-bounds-leak.stderr | 7 +- .../trivial-bounds/trivial-bounds-lint.stderr | 2 +- src/test/ui/trivial_casts.stderr | 4 +- .../ui/try-block/try-block-opt-init.stderr | 2 +- .../try-block-unreachable-code-lint.stderr | 2 +- .../ui/tuple/tuple-struct-fields/test2.stderr | 2 + .../ui/tuple/tuple-struct-fields/test3.stderr | 2 + ...ant-priority-higher-than-other-inherent.rs | 2 +- ...priority-higher-than-other-inherent.stderr | 6 +- ...riority-lint-ambiguous_associated_items.rs | 1 + ...ity-lint-ambiguous_associated_items.stderr | 4 +- .../type-alias-impl-trait/assoc-type-const.rs | 12 +- .../assoc-type-lifetime-unconstrained.rs | 26 + .../assoc-type-lifetime-unconstrained.stderr | 9 + .../assoc-type-lifetime.rs | 6 +- .../bound_reduction2.stderr | 7 +- .../generic_duplicate_lifetime_param.stderr | 8 +- .../generic_duplicate_param_use6.rs | 6 +- .../generic_duplicate_param_use6.stderr | 4 +- ...eric_type_does_not_live_long_enough.stderr | 2 +- .../generic_underconstrained.stderr | 8 +- .../generic_underconstrained2.stderr | 14 +- .../issue-52843-closure-constrain.rs | 2 +- .../issue-52843-closure-constrain.stderr | 18 +- .../type-alias-impl-trait/issue-60371.stderr | 2 +- .../ui/type-alias-impl-trait/issue-60564.rs | 2 +- .../ui/type-alias-impl-trait/issue-63279.rs | 2 + .../type-alias-impl-trait/issue-63279.stderr | 4 +- ...sue-65679-inst-opaque-ty-from-val-twice.rs | 1 + .../ui/type-alias-impl-trait/issue-65918.rs | 4 +- .../issue-67844-nested-opaque.rs | 32 + .../ui/type/ascription/issue-47666.stderr | 4 +- src/test/ui/type/ascription/issue-54516.rs | 4 +- .../ui/type/ascription/issue-54516.stderr | 28 +- src/test/ui/type/ascription/issue-60933.rs | 4 +- .../ui/type/ascription/issue-60933.stderr | 28 +- .../type-ascription-instead-of-initializer.rs | 2 +- ...e-ascription-instead-of-initializer.stderr | 6 +- ...ascription-instead-of-statement-end.stderr | 4 +- src/test/ui/type/type-check-defaults.stderr | 13 +- .../cannot_infer_local_or_vec.stderr | 2 +- ...cannot_infer_local_or_vec_in_tuples.stderr | 2 +- src/test/ui/type/type-check/issue-40294.rs | 4 +- .../ui/type/type-check/issue-40294.stderr | 16 +- ...ter-defaults-referencing-Self-ppaux.stderr | 6 +- ...-52082-type-param-shadows-existing-type.rs | 2 +- ...ypeck-default-trait-impl-send-param.stderr | 7 +- .../ui/typeck/typeck_type_placeholder_item.rs | 208 + .../typeck_type_placeholder_item.stderr | 608 + src/test/ui/ufcs/ufcs-partially-resolved.rs | 4 +- .../ui/ufcs/ufcs-partially-resolved.stderr | 10 +- .../unboxed-closure-feature-gate.stderr | 2 +- .../unboxed-closure-no-cyclic-sig.stderr | 3 +- ...oxed-closure-sugar-lifetime-elision.stderr | 4 +- ...nboxed-closure-sugar-not-used-on-fn.stderr | 4 +- .../unboxed-closures-mutate-upvar.stderr | 16 +- ...sures-mutated-upvar-from-fn-closure.stderr | 16 +- .../unboxed-closures-unique-type-id.rs | 2 +- src/test/ui/underscore-imports/basic.stderr | 2 +- .../ui/underscore-imports/unused-2018.stderr | 2 +- .../dyn-trait-underscore-in-struct.stderr | 4 +- .../ui/underscore-lifetime/in-binder.stderr | 1 + .../in-fn-return-illegal.stderr | 6 +- .../ui/underscore-lifetime/in-struct.stderr | 8 +- .../underscore-lifetime-binders.stderr | 9 +- .../underscore-outlives-bounds.stderr | 1 + ...se-inherent-impl-ampersand.rust2015.stderr | 1 + ...se-inherent-impl-ampersand.rust2018.stderr | 1 + ...e-inherent-impl-underscore.rust2015.stderr | 1 + ...e-inherent-impl-underscore.rust2018.stderr | 1 + ...e-clause-trait-impl-region.rust2015.stderr | 1 + ...e-clause-trait-impl-region.rust2018.stderr | 1 + ...ause-trait-impl-underscore.rust2015.stderr | 1 + ...ause-trait-impl-underscore.rust2018.stderr | 1 + .../underscore-lifetime/where-clauses.stderr | 1 + .../uninhabited/uninhabited-patterns.stderr | 2 +- src/test/ui/union/union-derive-clone.stderr | 15 +- src/test/ui/union/union-derive-eq.stderr | 1 + src/test/ui/union/union-fields-1.stderr | 2 +- src/test/ui/union/union-lint-dead-code.stderr | 2 +- src/test/ui/union/union-repr-c.stderr | 4 +- src/test/ui/union/union-sized-field.stderr | 6 +- src/test/ui/unique-object-noncopyable.rs | 4 + src/test/ui/unique-object-noncopyable.stderr | 21 +- src/test/ui/unique-pinned-nocopy.rs | 4 + src/test/ui/unique-pinned-nocopy.stderr | 13 +- src/test/ui/unnecessary-extern-crate.stderr | 2 +- src/test/ui/unop-move-semantics.stderr | 10 +- src/test/ui/unop-neg-bool.stderr | 2 - src/test/ui/unreachable-code-ret.stderr | 4 +- src/test/ui/unsafe/ranged_ints2_const.stderr | 4 +- ...fe-around-compiler-generated-unsafe.stderr | 2 +- .../ui/unsafe/unsafe-block-without-braces.rs | 2 +- .../unsafe/unsafe-block-without-braces.stderr | 4 +- .../by-value-trait-object-safety.stderr | 3 + .../ui/unsized/unsized-bare-typaram.stderr | 4 +- src/test/ui/unsized/unsized-enum.stderr | 4 +- src/test/ui/unsized/unsized-enum2.stderr | 8 +- .../unsized-inherent-impl-self-type.stderr | 4 +- src/test/ui/unsized/unsized-struct.stderr | 8 +- .../unsized-trait-impl-self-type.stderr | 4 +- .../unsized-trait-impl-trait-arg.stderr | 4 +- src/test/ui/unsized3.stderr | 20 +- src/test/ui/unsized5.stderr | 8 +- src/test/ui/unsized6.stderr | 30 +- src/test/ui/unsized7.stderr | 4 +- src/test/ui/unused/unused-attr.stderr | 2 +- src/test/ui/unused/unused-macro-rules.stderr | 6 +- src/test/ui/unused/unused-macro.stderr | 4 +- .../unused-mut-warning-captured-var.stderr | 2 +- src/test/ui/unused/unused-result.rs | 4 +- src/test/ui/unused/unused-result.stderr | 4 +- src/test/ui/use-module-level-int-consts.rs | 11 + .../use-nested-groups-unused-imports.stderr | 2 +- src/test/ui/useless-comment.stderr | 24 +- src/test/ui/utf8_idents.stderr | 8 +- .../variants/variant-size-differences.stderr | 2 +- src/test/ui/vec/vec-res-add.stderr | 2 - src/test/ui/wf/wf-array-elem-sized.rs | 2 +- .../wf/wf-convert-unsafe-trait-obj-box.stderr | 18 +- .../ui/wf/wf-convert-unsafe-trait-obj.stderr | 18 +- src/test/ui/wf/wf-enum-bound.rs | 4 +- src/test/ui/wf/wf-enum-bound.stderr | 23 +- .../wf/wf-enum-fields-struct-variant.stderr | 9 +- src/test/ui/wf/wf-enum-fields.stderr | 8 +- src/test/ui/wf/wf-fn-where-clause.stderr | 31 +- .../wf/wf-impl-associated-type-region.stderr | 2 +- .../wf/wf-impl-associated-type-trait.stderr | 8 +- src/test/ui/wf/wf-in-fn-arg.stderr | 21 +- src/test/ui/wf/wf-in-fn-ret.stderr | 21 +- src/test/ui/wf/wf-in-fn-type-arg.stderr | 9 +- src/test/ui/wf/wf-in-fn-type-ret.stderr | 9 +- src/test/ui/wf/wf-in-fn-type-static.stderr | 4 +- src/test/ui/wf/wf-in-fn-where-clause.rs | 4 +- src/test/ui/wf/wf-in-fn-where-clause.stderr | 20 +- src/test/ui/wf/wf-in-obj-type-static.stderr | 2 +- src/test/ui/wf/wf-in-obj-type-trait.stderr | 9 +- ...f-inherent-impl-method-where-clause.stderr | 19 +- .../wf/wf-inherent-impl-where-clause.stderr | 21 +- src/test/ui/wf/wf-object-safe.stderr | 6 +- .../wf/wf-outlives-ty-in-fn-or-trait.stderr | 4 +- src/test/ui/wf/wf-struct-bound.rs | 4 +- src/test/ui/wf/wf-struct-bound.stderr | 23 +- src/test/ui/wf/wf-struct-field.stderr | 8 +- .../ui/wf/wf-trait-associated-type-bound.rs | 4 +- .../wf/wf-trait-associated-type-bound.stderr | 23 +- src/test/ui/wf/wf-trait-bound.rs | 4 +- src/test/ui/wf/wf-trait-bound.stderr | 22 +- src/test/ui/wf/wf-trait-default-fn-arg.stderr | 19 +- src/test/ui/wf/wf-trait-default-fn-ret.stderr | 20 +- .../wf-trait-default-fn-where-clause.stderr | 19 +- src/test/ui/wf/wf-trait-fn-arg.stderr | 9 +- src/test/ui/wf/wf-trait-fn-ret.stderr | 9 +- .../ui/wf/wf-trait-fn-where-clause.stderr | 9 +- src/test/ui/wf/wf-trait-superbound.stderr | 20 +- .../ui/wf/wf-unsafe-trait-obj-match.stderr | 12 +- ...traints-are-local-for-inherent-impl.stderr | 9 +- ...onstraints-are-local-for-trait-impl.stderr | 9 +- .../where-equality-constraints.stderr | 4 +- src/test/ui/while-let.stderr | 3 + src/tools/compiletest/src/common.rs | 1 - src/tools/compiletest/src/errors.rs | 2 +- src/tools/compiletest/src/header.rs | 248 +- src/tools/compiletest/src/header/tests.rs | 173 +- src/tools/compiletest/src/main.rs | 5 +- src/tools/compiletest/src/runtest.rs | 42 +- src/tools/error_index_generator/main.rs | 4 +- src/tools/linkchecker/linkcheck.sh | 113 + src/tools/publish_toolstate.py | 36 +- src/tools/rustbook/Cargo.toml | 3 +- src/tools/rustbook/src/main.rs | 108 +- src/tools/tidy/src/deps.rs | 3 +- src/tools/tidy/src/features.rs | 14 - src/tools/tidy/src/lib.rs | 1 + src/tools/tidy/src/pal.rs | 4 +- src/tools/tidy/src/unstable_book.rs | 18 +- src/tools/unicode-table-generator/src/main.rs | 2 +- vendor/backtrace/.cargo-checksum.json | 2 +- vendor/backtrace/Cargo.lock | 210 +- vendor/backtrace/Cargo.toml | 8 +- .../docker/aarch64-linux-android/Dockerfile | 2 +- .../docker/armv7-linux-androideabi/Dockerfile | 2 +- .../ci/docker/i686-linux-android/Dockerfile | 2 +- .../powerpc64-unknown-linux-gnu/Dockerfile | 2 +- .../ci/docker/x86_64-linux-android/Dockerfile | 2 +- .../docker/x86_64-pc-windows-gnu/Dockerfile | 2 +- vendor/backtrace/src/backtrace/dbghelp.rs | 40 +- vendor/backtrace/src/backtrace/libunwind.rs | 93 +- vendor/backtrace/src/backtrace/mod.rs | 5 +- vendor/backtrace/src/lib.rs | 5 +- vendor/backtrace/src/print.rs | 3 +- vendor/backtrace/src/symbolize/gimli.rs | 30 +- .../backtrace/src/symbolize/libbacktrace.rs | 52 +- vendor/backtrace/src/symbolize/mod.rs | 4 +- vendor/backtrace/src/windows.rs | 28 +- vendor/chalk-engine/.cargo-checksum.json | 1 - vendor/chalk-engine/Cargo.toml | 34 - vendor/chalk-engine/README.md | 3 - vendor/chalk-engine/src/README.md | 280 - vendor/chalk-engine/src/context.rs | 378 - vendor/chalk-engine/src/context/prelude.rs | 8 - vendor/chalk-engine/src/derived.rs | 92 - vendor/chalk-engine/src/fallible.rs | 8 - vendor/chalk-engine/src/forest.rs | 181 - vendor/chalk-engine/src/hh.rs | 25 - vendor/chalk-engine/src/lib.rs | 334 - vendor/chalk-engine/src/logic.rs | 1341 --- vendor/chalk-engine/src/simplify.rs | 79 - vendor/chalk-engine/src/stack.rs | 79 - vendor/chalk-engine/src/strand.rs | 46 - vendor/chalk-engine/src/table.rs | 139 - vendor/chalk-engine/src/tables.rs | 66 - vendor/chalk-macros/.cargo-checksum.json | 1 - vendor/chalk-macros/Cargo.toml | 23 - vendor/chalk-macros/README.md | 1 - vendor/chalk-macros/src/index.rs | 73 - vendor/chalk-macros/src/lib.rs | 137 - vendor/crossbeam-channel/.cargo-checksum.json | 2 +- vendor/crossbeam-channel/CHANGELOG.md | 12 + vendor/crossbeam-channel/Cargo.lock | 251 + vendor/crossbeam-channel/Cargo.toml | 12 +- vendor/crossbeam-channel/LICENSE-MIT | 4 + vendor/crossbeam-channel/README.md | 9 +- vendor/crossbeam-channel/benches/crossbeam.rs | 715 ++ vendor/crossbeam-channel/examples/matching.rs | 3 +- vendor/crossbeam-channel/src/channel.rs | 67 +- vendor/crossbeam-channel/src/context.rs | 6 +- vendor/crossbeam-channel/src/counter.rs | 36 +- vendor/crossbeam-channel/src/err.rs | 16 +- vendor/crossbeam-channel/src/flavors/array.rs | 69 +- vendor/crossbeam-channel/src/flavors/list.rs | 59 +- vendor/crossbeam-channel/src/flavors/tick.rs | 2 +- vendor/crossbeam-channel/src/flavors/zero.rs | 15 +- vendor/crossbeam-channel/src/lib.rs | 10 +- vendor/crossbeam-channel/src/select.rs | 178 +- vendor/crossbeam-channel/src/select_macro.rs | 45 +- vendor/crossbeam-channel/src/utils.rs | 40 +- vendor/crossbeam-channel/src/waker.rs | 8 +- vendor/crossbeam-channel/tests/after.rs | 12 +- vendor/crossbeam-channel/tests/array.rs | 89 +- vendor/crossbeam-channel/tests/golang.rs | 503 +- vendor/crossbeam-channel/tests/iter.rs | 9 +- vendor/crossbeam-channel/tests/list.rs | 74 +- vendor/crossbeam-channel/tests/mpsc.rs | 411 +- vendor/crossbeam-channel/tests/ready.rs | 55 +- .../crossbeam-channel/tests/same_channel.rs | 114 + vendor/crossbeam-channel/tests/select.rs | 187 +- .../crossbeam-channel/tests/select_macro.rs | 126 +- .../crossbeam-channel/tests/thread_locals.rs | 4 +- vendor/crossbeam-channel/tests/tick.rs | 9 +- vendor/crossbeam-channel/tests/zero.rs | 98 +- vendor/crossbeam-utils/.cargo-checksum.json | 1 + vendor/crossbeam-utils/CHANGELOG.md | 104 + vendor/crossbeam-utils/Cargo.toml | 40 + .../LICENSE-APACHE | 0 vendor/crossbeam-utils/LICENSE-MIT | 27 + vendor/crossbeam-utils/README.md | 77 + vendor/crossbeam-utils/benches/atomic_cell.rs | 157 + vendor/crossbeam-utils/build.rs | 8 + .../crossbeam-utils/src/atomic/atomic_cell.rs | 902 ++ vendor/crossbeam-utils/src/atomic/consume.rs | 82 + vendor/crossbeam-utils/src/atomic/mod.rs | 25 + vendor/crossbeam-utils/src/atomic/seq_lock.rs | 88 + .../src/atomic/seq_lock_wide.rs | 132 + vendor/crossbeam-utils/src/backoff.rs | 292 + vendor/crossbeam-utils/src/cache_padded.rs | 131 + vendor/crossbeam-utils/src/lib.rs | 64 + vendor/crossbeam-utils/src/sync/mod.rs | 17 + vendor/crossbeam-utils/src/sync/parker.rs | 311 + .../crossbeam-utils/src/sync/sharded_lock.rs | 600 + vendor/crossbeam-utils/src/sync/wait_group.rs | 139 + vendor/crossbeam-utils/src/thread.rs | 529 + vendor/crossbeam-utils/tests/atomic_cell.rs | 234 + vendor/crossbeam-utils/tests/cache_padded.rs | 112 + vendor/crossbeam-utils/tests/parker.rs | 43 + vendor/crossbeam-utils/tests/sharded_lock.rs | 255 + vendor/crossbeam-utils/tests/thread.rs | 181 + vendor/crossbeam-utils/tests/wait_group.rs | 66 + vendor/filetime/.cargo-checksum.json | 2 +- vendor/filetime/Cargo.toml | 16 +- vendor/filetime/README.md | 13 +- vendor/filetime/appveyor.yml | 17 - vendor/filetime/src/lib.rs | 258 +- vendor/filetime/src/redox.rs | 25 +- vendor/filetime/src/unix/linux.rs | 122 +- vendor/filetime/src/unix/macos.rs | 110 + vendor/filetime/src/unix/mod.rs | 76 +- vendor/filetime/src/unix/utimensat.rs | 57 +- vendor/filetime/src/unix/utimes.rs | 97 +- vendor/filetime/src/wasm.rs | 40 + vendor/filetime/src/windows.rs | 88 +- vendor/ignore/.cargo-checksum.json | 2 +- vendor/ignore/Cargo.lock | 75 +- vendor/ignore/Cargo.toml | 6 +- vendor/ignore/src/dir.rs | 325 +- vendor/ignore/src/gitignore.rs | 6 +- vendor/ignore/src/types.rs | 2 +- vendor/ignore/src/walk.rs | 437 +- vendor/kernel32-sys/.cargo-checksum.json | 1 - vendor/kernel32-sys/Cargo.toml | 17 - vendor/kernel32-sys/README.md | 13 - vendor/kernel32-sys/build.rs | 6 - vendor/kernel32-sys/src/lib.rs | 2754 ----- .../lazy_static-0.2.11/.cargo-checksum.json | 1 - vendor/lazy_static-0.2.11/Cargo.toml | 43 - vendor/lazy_static-0.2.11/LICENSE-MIT | 25 - vendor/lazy_static-0.2.11/README.md | 69 - vendor/lazy_static-0.2.11/appveyor.yml | 59 - vendor/lazy_static-0.2.11/src/core_lazy.rs | 33 - vendor/lazy_static-0.2.11/src/lazy.rs | 39 - vendor/lazy_static-0.2.11/src/lib.rs | 212 - vendor/lazy_static-0.2.11/src/nightly_lazy.rs | 43 - .../tests/compile-fail/README.md | 22 - .../incorrect_visibility_restriction.rs | 10 - .../tests/compile-fail/static_is_private.rs | 14 - .../tests/compile-fail/static_is_sized.rs | 11 - .../tests/compile-fail/static_never_used.rs | 10 - .../lazy_static-0.2.11/tests/compile_tests.rs | 18 - vendor/lazy_static-0.2.11/tests/no_std.rs | 21 - vendor/lazy_static-0.2.11/tests/test.rs | 164 - vendor/memchr/.cargo-checksum.json | 2 +- vendor/memchr/Cargo.toml | 16 +- vendor/memchr/README.md | 45 +- vendor/memchr/build.rs | 79 +- vendor/memchr/rustfmt.toml | 2 + vendor/memchr/src/fallback.rs | 80 +- vendor/memchr/src/iter.rs | 10 +- vendor/memchr/src/lib.rs | 207 +- vendor/memchr/src/naive.rs | 24 +- vendor/memchr/src/tests/iter.rs | 11 +- vendor/memchr/src/tests/miri.rs | 19 + vendor/memchr/src/tests/mod.rs | 126 +- vendor/memchr/src/x86/avx.rs | 70 +- vendor/memchr/src/x86/mod.rs | 26 +- vendor/memchr/src/x86/sse2.rs | 72 +- .../.cargo-checksum.json | 0 .../CHANGELOG.md | 0 .../Cargo.toml | 0 .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../README.md | 0 .../appveyor.yml | 0 .../build.rs | 0 .../src/condvar.rs | 0 .../src/deadlock.rs | 0 .../src/elision.rs | 0 .../src/lib.rs | 0 .../src/mutex.rs | 0 .../src/once.rs | 0 .../src/raw_mutex.rs | 0 .../src/raw_rwlock.rs | 0 .../src/remutex.rs | 0 .../src/rwlock.rs | 0 .../src/util.rs | 0 .../.cargo-checksum.json | 0 .../Cargo.toml | 0 .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../build.rs | 0 .../src/lib.rs | 0 .../src/parking_lot.rs | 0 .../src/spinwait.rs | 0 .../src/thread_parker/cloudabi.rs | 0 .../src/thread_parker/generic.rs | 0 .../src/thread_parker/linux.rs | 0 .../src/thread_parker/mod.rs | 0 .../src/thread_parker/redox.rs | 0 .../src/thread_parker/sgx.rs | 0 .../src/thread_parker/unix.rs | 0 .../src/thread_parker/wasm.rs | 0 .../src/thread_parker/wasm_atomic.rs | 0 .../src/thread_parker/windows/keyed_event.rs | 0 .../src/thread_parker/windows/mod.rs | 0 .../src/thread_parker/windows/waitaddress.rs | 0 .../src/util.rs | 0 .../src/word_lock.rs | 0 vendor/polonius-engine/.cargo-checksum.json | 2 +- vendor/polonius-engine/Cargo.toml | 2 +- vendor/polonius-engine/src/facts.rs | 73 +- .../src/output/datafrog_opt.rs | 62 +- .../src/output/initialization.rs | 303 +- vendor/polonius-engine/src/output/liveness.rs | 148 +- .../src/output/location_insensitive.rs | 8 +- vendor/polonius-engine/src/output/mod.rs | 99 +- vendor/polonius-engine/src/output/naive.rs | 30 +- .../pulldown-cmark-0.5.3/.cargo-checksum.json | 1 - vendor/pulldown-cmark-0.5.3/CONTRIBUTING.md | 11 - vendor/pulldown-cmark-0.5.3/Cargo.toml | 64 - vendor/pulldown-cmark-0.5.3/README.md | 150 - .../pulldown-cmark-0.5.3/azure-pipelines.yml | 17 - vendor/pulldown-cmark-0.5.3/benches/lib.rs | 151 - .../pulldown-cmark-0.5.3/specs/footnotes.txt | 153 - .../pulldown-cmark-0.5.3/specs/regression.txt | 482 - vendor/pulldown-cmark-0.5.3/specs/table.txt | 217 - vendor/pulldown-cmark-0.5.3/src/lib.rs | 74 - vendor/pulldown-cmark-0.5.3/src/main.rs | 290 - .../tests/suite/regression.rs | 557 - .../third_party/CommonMark/LICENSE | 105 - .../third_party/CommonMark/README.google | 12 - .../third_party/CommonMark/spec.txt | 9710 --------------- .../third_party/GitHub/LICENSE | 170 - .../third_party/GitHub/gfm_strikethrough.txt | 27 - .../third_party/GitHub/gfm_table.txt | 209 - .../third_party/GitHub/gfm_tasklist.txt | 55 - .../third_party/GitHub/spec.txt | 10041 ---------------- .../third_party/xi-editor/LICENSE | 203 - .../third_party/xi-editor/crdt.md | 1097 -- .../pulldown-cmark-0.5.3/tools/mk_entities.py | 74 - .../tools/mk_puncttable.py | 130 - .../pulldown-cmark-0.6.1/.cargo-checksum.json | 1 + vendor/pulldown-cmark-0.6.1/CONTRIBUTING.md | 21 + vendor/pulldown-cmark-0.6.1/Cargo.lock | 871 ++ vendor/pulldown-cmark-0.6.1/Cargo.toml | 65 + .../LICENSE | 0 vendor/pulldown-cmark-0.6.1/README.md | 152 + .../benches/html_rendering.rs | 0 vendor/pulldown-cmark-0.6.1/benches/lib.rs | 49 + .../build.rs | 0 .../examples/event-filter.rs | 0 .../examples/string-to-string.rs | 0 .../src/entities.rs | 0 .../src/escape.rs | 41 +- .../src/html.rs | 28 +- vendor/pulldown-cmark-0.6.1/src/lib.rs | 74 + .../src/linklabel.rs | 29 +- vendor/pulldown-cmark-0.6.1/src/main.rs | 109 + .../src/parse.rs | 587 +- .../src/puncttable.rs | 0 .../src/scanners.rs | 227 +- .../src/simd.rs | 0 .../src/strings.rs | 33 +- .../src/tree.rs | 0 .../tests/errors.rs | 0 .../tests/html.rs | 0 .../tests/lib.rs | 0 .../tests/suite/footnotes.rs | 0 .../tests/suite/gfm_strikethrough.rs | 0 .../tests/suite/gfm_table.rs | 0 .../tests/suite/gfm_tasklist.rs | 0 .../tests/suite/mod.rs | 0 .../tests/suite/regression.rs | 807 ++ .../tests/suite/spec.rs | 0 .../tests/suite/table.rs | 0 vendor/pulldown-cmark/.cargo-checksum.json | 2 +- vendor/pulldown-cmark/Cargo.lock | 556 +- vendor/pulldown-cmark/Cargo.toml | 6 +- vendor/pulldown-cmark/README.md | 4 +- vendor/pulldown-cmark/src/html.rs | 21 +- vendor/pulldown-cmark/src/lib.rs | 4 +- vendor/pulldown-cmark/src/parse.rs | 107 +- vendor/pulldown-cmark/src/scanners.rs | 2 +- .../pulldown-cmark/tests/suite/regression.rs | 46 +- vendor/pulldown-cmark/tests/suite/spec.rs | 9 +- vendor/pulldown-cmark/tests/suite/table.rs | 3 +- vendor/tar/.cargo-checksum.json | 2 +- vendor/tar/Cargo.toml | 8 +- vendor/tar/README.md | 6 +- vendor/tar/src/archive.rs | 13 +- vendor/tar/src/builder.rs | 165 +- vendor/tar/src/entry.rs | 193 +- vendor/tar/src/error.rs | 2 +- vendor/tar/src/header.rs | 59 +- vendor/tar/src/lib.rs | 22 +- vendor/tar/src/pax.rs | 2 +- vendor/tar/tests/all.rs | 156 +- vendor/tar/tests/archives/directory.tar | Bin 10240 -> 0 bytes vendor/tar/tests/archives/duplicate_dirs.tar | Bin 2048 -> 0 bytes vendor/tar/tests/archives/empty_filename.tar | Bin 512 -> 0 bytes vendor/tar/tests/archives/file_times.tar | Bin 1536 -> 0 bytes vendor/tar/tests/archives/link.tar | Bin 10240 -> 0 bytes vendor/tar/tests/archives/pax.tar | Bin 10240 -> 0 bytes vendor/tar/tests/archives/pax2.tar | Bin 10240 -> 0 bytes vendor/tar/tests/archives/reading_files.tar | Bin 10240 -> 0 bytes vendor/tar/tests/archives/simple.tar | Bin 10240 -> 0 bytes .../archives/simple_missing_last_header.tar | Bin 9728 -> 0 bytes vendor/tar/tests/archives/spaces.tar | Bin 2048 -> 0 bytes vendor/tar/tests/archives/sparse.tar | Bin 10240 -> 0 bytes vendor/tar/tests/archives/xattrs.tar | Bin 10240 -> 0 bytes vendor/tar/tests/entry.rs | 26 + vendor/term_size/.cargo-checksum.json | 1 - vendor/term_size/CHANGELOG.md | 48 - vendor/term_size/CONTRIBUTORS.md | 11 - vendor/term_size/Cargo.toml | 84 - vendor/term_size/LICENSE-MIT | 21 - vendor/term_size/README.md | 63 - vendor/term_size/appveyor.yml | 12 - vendor/term_size/index.html | 1 - vendor/term_size/justfile | 39 - vendor/term_size/rustfmt.toml | 4 - vendor/term_size/src/lib.rs | 237 - vendor/termize/.cargo-checksum.json | 1 + vendor/termize/CHANGELOG.md | 9 + vendor/termize/CODE_OF_CONDUCT.md | 76 + vendor/termize/CONTRIBUTING.md | 22 + vendor/termize/Cargo.toml | 56 + vendor/{term_size => termize}/LICENSE-APACHE | 0 vendor/termize/LICENSE-MIT | 22 + vendor/termize/README.md | 51 + vendor/termize/src/lib.rs | 34 + vendor/termize/src/platform/mod.rs | 15 + vendor/termize/src/platform/unix.rs | 232 + vendor/termize/src/platform/unsupported.rs | 12 + vendor/termize/src/platform/windows.rs | 107 + .../thread_local-0.3.6/.cargo-checksum.json | 1 + vendor/thread_local-0.3.6/Cargo.toml | 26 + .../LICENSE-APACHE | 0 vendor/thread_local-0.3.6/LICENSE-MIT | 25 + vendor/thread_local-0.3.6/README.md | 41 + .../benches/thread_local.rs | 18 + vendor/thread_local-0.3.6/src/lib.rs | 757 ++ vendor/thread_local-0.3.6/src/thread_id.rs | 61 + vendor/thread_local-0.3.6/src/unreachable.rs | 74 + vendor/thread_local/.cargo-checksum.json | 2 +- vendor/thread_local/Cargo.toml | 4 +- vendor/thread_local/README.md | 2 +- vendor/thread_local/src/cached.rs | 198 + vendor/thread_local/src/lib.rs | 330 +- vendor/unicase/.cargo-checksum.json | 2 +- vendor/unicase/Cargo.toml | 8 +- vendor/unicase/build.rs | 14 +- vendor/unicase/src/ascii.rs | 14 +- vendor/unicase/src/lib.rs | 47 +- vendor/unicase/src/unicode/map.rs | 2 +- vendor/unicase/src/unicode/mod.rs | 26 +- .../version_check-0.1.5/.cargo-checksum.json | 1 - vendor/version_check-0.1.5/Cargo.toml | 24 - vendor/version_check-0.1.5/README.md | 67 - vendor/version_check-0.1.5/src/lib.rs | 255 - vendor/version_check/.cargo-checksum.json | 1 + vendor/version_check/Cargo.toml | 24 + vendor/version_check/LICENSE-APACHE | 201 + .../LICENSE-MIT | 0 vendor/version_check/README.md | 76 + vendor/version_check/src/channel.rs | 192 + vendor/version_check/src/date.rs | 167 + vendor/version_check/src/lib.rs | 288 + vendor/version_check/src/version.rs | 238 + vendor/winapi-0.2.8/.cargo-checksum.json | 1 - vendor/winapi-0.2.8/Cargo.toml | 61 - vendor/winapi-0.2.8/LICENSE.md | 21 - vendor/winapi-0.2.8/src/activation.rs | 5 - vendor/winapi-0.2.8/src/audioclient.rs | 71 - vendor/winapi-0.2.8/src/audiosessiontypes.rs | 11 - vendor/winapi-0.2.8/src/basetsd.rs | 99 - vendor/winapi-0.2.8/src/bcrypt.rs | 356 - vendor/winapi-0.2.8/src/cfg.rs | 134 - vendor/winapi-0.2.8/src/cfgmgr32.rs | 758 -- vendor/winapi-0.2.8/src/combaseapi.rs | 17 - vendor/winapi-0.2.8/src/commctrl.rs | 3578 ------ vendor/winapi-0.2.8/src/commdlg.rs | 583 - vendor/winapi-0.2.8/src/corsym.rs | 79 - vendor/winapi-0.2.8/src/d2d1.rs | 734 -- vendor/winapi-0.2.8/src/d2dbasetypes.rs | 61 - vendor/winapi-0.2.8/src/d3d10shader.rs | 110 - vendor/winapi-0.2.8/src/d3d11.rs | 2665 ---- vendor/winapi-0.2.8/src/d3d11shader.rs | 320 - vendor/winapi-0.2.8/src/d3d12.rs | 2324 ---- vendor/winapi-0.2.8/src/d3d12sdklayers.rs | 1063 -- vendor/winapi-0.2.8/src/d3d12shader.rs | 320 - vendor/winapi-0.2.8/src/d3d9.rs | 713 -- vendor/winapi-0.2.8/src/d3d9caps.rs | 349 - vendor/winapi-0.2.8/src/d3d9types.rs | 1397 --- vendor/winapi-0.2.8/src/d3dcommon.rs | 753 -- vendor/winapi-0.2.8/src/d3dcompiler.rs | 74 - vendor/winapi-0.2.8/src/dbghelp.rs | 340 - vendor/winapi-0.2.8/src/dcommon.rs | 18 - vendor/winapi-0.2.8/src/devpropdef.rs | 71 - vendor/winapi-0.2.8/src/docobj.rs | 22 - vendor/winapi-0.2.8/src/dpapi.rs | 11 - vendor/winapi-0.2.8/src/dsgetdc.rs | 113 - vendor/winapi-0.2.8/src/dsound.rs | 132 - vendor/winapi-0.2.8/src/dsrole.rs | 50 - vendor/winapi-0.2.8/src/dwmapi.rs | 9 - vendor/winapi-0.2.8/src/dwrite.rs | 1038 -- vendor/winapi-0.2.8/src/dxgi.rs | 240 - vendor/winapi-0.2.8/src/dxgi1_2.rs | 288 - vendor/winapi-0.2.8/src/dxgi1_3.rs | 131 - vendor/winapi-0.2.8/src/dxgi1_4.rs | 82 - vendor/winapi-0.2.8/src/dxgiformat.rs | 124 - vendor/winapi-0.2.8/src/dxgitype.rs | 86 - vendor/winapi-0.2.8/src/errhandlingapi.rs | 7 - vendor/winapi-0.2.8/src/excpt.rs | 14 - vendor/winapi-0.2.8/src/fileapi.rs | 152 - vendor/winapi-0.2.8/src/gl.rs | 35 - vendor/winapi-0.2.8/src/guiddef.rs | 20 - vendor/winapi-0.2.8/src/heapapi.rs | 12 - vendor/winapi-0.2.8/src/hidclass.rs | 56 - vendor/winapi-0.2.8/src/hidpi.rs | 182 - vendor/winapi-0.2.8/src/hidsdi.rs | 15 - vendor/winapi-0.2.8/src/hidusage.rs | 270 - vendor/winapi-0.2.8/src/hstring.rs | 16 - vendor/winapi-0.2.8/src/http.rs | 828 -- vendor/winapi-0.2.8/src/imm.rs | 3 - vendor/winapi-0.2.8/src/inaddr.rs | 22 - vendor/winapi-0.2.8/src/inspectable.rs | 15 - vendor/winapi-0.2.8/src/ksmedia.rs | 18 - vendor/winapi-0.2.8/src/lib.rs | 368 - vendor/winapi-0.2.8/src/libloaderapi.rs | 23 - vendor/winapi-0.2.8/src/lmaccess.rs | 853 -- vendor/winapi-0.2.8/src/lmcons.rs | 55 - vendor/winapi-0.2.8/src/lmdfs.rs | 311 - vendor/winapi-0.2.8/src/lmerrlog.rs | 263 - vendor/winapi-0.2.8/src/lmjoin.rs | 80 - vendor/winapi-0.2.8/src/lsalookup.rs | 69 - vendor/winapi-0.2.8/src/macros.rs | 270 - vendor/winapi-0.2.8/src/memoryapi.rs | 19 - vendor/winapi-0.2.8/src/minschannel.rs | 56 - vendor/winapi-0.2.8/src/minwinbase.rs | 253 - vendor/winapi-0.2.8/src/minwindef.rs | 89 - vendor/winapi-0.2.8/src/mmdeviceapi.rs | 63 - vendor/winapi-0.2.8/src/mmreg.rs | 304 - vendor/winapi-0.2.8/src/mmsystem.rs | 259 - vendor/winapi-0.2.8/src/mscat.rs | 28 - vendor/winapi-0.2.8/src/mssip.rs | 103 - vendor/winapi-0.2.8/src/nb30.rs | 200 - vendor/winapi-0.2.8/src/ncrypt.rs | 9 - vendor/winapi-0.2.8/src/ntdef.rs | 7 - vendor/winapi-0.2.8/src/ntsecapi.rs | 1589 --- vendor/winapi-0.2.8/src/ntstatus.rs | 2474 ---- vendor/winapi-0.2.8/src/oaidl.rs | 590 - vendor/winapi-0.2.8/src/objbase.rs | 5 - vendor/winapi-0.2.8/src/objidl.rs | 100 - vendor/winapi-0.2.8/src/objidlbase.rs | 93 - vendor/winapi-0.2.8/src/olectl.rs | 10 - vendor/winapi-0.2.8/src/pdh.rs | 52 - vendor/winapi-0.2.8/src/playsoundapi.rs | 19 - vendor/winapi-0.2.8/src/processsnapshot.rs | 58 - vendor/winapi-0.2.8/src/processthreadsapi.rs | 62 - vendor/winapi-0.2.8/src/propidl.rs | 10 - vendor/winapi-0.2.8/src/propsys.rs | 4 - vendor/winapi-0.2.8/src/prsht.rs | 262 - vendor/winapi-0.2.8/src/psapi.rs | 166 - vendor/winapi-0.2.8/src/qos.rs | 16 - vendor/winapi-0.2.8/src/reason.rs | 63 - .../winapi-0.2.8/src/restrictederrorinfo.rs | 9 - vendor/winapi-0.2.8/src/roapi.rs | 13 - vendor/winapi-0.2.8/src/roerrorapi.rs | 11 - vendor/winapi-0.2.8/src/rpc.rs | 5 - vendor/winapi-0.2.8/src/rpcdce.rs | 535 - vendor/winapi-0.2.8/src/sapi.rs | 2431 ---- vendor/winapi-0.2.8/src/schannel.rs | 333 - vendor/winapi-0.2.8/src/servprov.rs | 11 - vendor/winapi-0.2.8/src/setupapi.rs | 1301 -- vendor/winapi-0.2.8/src/shellapi.rs | 62 - vendor/winapi-0.2.8/src/shellscalingapi.rs | 19 - vendor/winapi-0.2.8/src/shlguid.rs | 2 - vendor/winapi-0.2.8/src/shlobj.rs | 94 - vendor/winapi-0.2.8/src/shobjidl.rs | 652 - vendor/winapi-0.2.8/src/shtypes.rs | 40 - vendor/winapi-0.2.8/src/spapidef.rs | 48 - vendor/winapi-0.2.8/src/sql.rs | 179 - vendor/winapi-0.2.8/src/sqltypes.rs | 130 - vendor/winapi-0.2.8/src/sspi.rs | 657 - vendor/winapi-0.2.8/src/strmif.rs | 4 - vendor/winapi-0.2.8/src/subauth.rs | 198 - vendor/winapi-0.2.8/src/synchapi.rs | 14 - vendor/winapi-0.2.8/src/sysinfoapi.rs | 46 - vendor/winapi-0.2.8/src/threadpoolapi.rs | 7 - vendor/winapi-0.2.8/src/timezoneapi.rs | 27 - vendor/winapi-0.2.8/src/tlhelp32.rs | 104 - vendor/winapi-0.2.8/src/unknwnbase.rs | 29 - vendor/winapi-0.2.8/src/urlhist.rs | 56 - vendor/winapi-0.2.8/src/urlmon.rs | 6 - vendor/winapi-0.2.8/src/usb.rs | 18 - vendor/winapi-0.2.8/src/usbspec.rs | 41 - vendor/winapi-0.2.8/src/usp10.rs | 201 - vendor/winapi-0.2.8/src/vadefs.rs | 7 - vendor/winapi-0.2.8/src/vsbackup.rs | 303 - vendor/winapi-0.2.8/src/vss.rs | 256 - vendor/winapi-0.2.8/src/vsserror.rs | 85 - vendor/winapi-0.2.8/src/vswriter.rs | 241 - vendor/winapi-0.2.8/src/werapi.rs | 8 - vendor/winapi-0.2.8/src/winbase.rs | 552 - vendor/winapi-0.2.8/src/wincon.rs | 198 - vendor/winapi-0.2.8/src/wincred.rs | 209 - vendor/winapi-0.2.8/src/wincrypt.rs | 2206 ---- vendor/winapi-0.2.8/src/windef.rs | 57 - vendor/winapi-0.2.8/src/windowscodecs.rs | 363 - vendor/winapi-0.2.8/src/windowsx.rs | 22 - vendor/winapi-0.2.8/src/winerror.rs | 6065 ---------- vendor/winapi-0.2.8/src/winevt.rs | 40 - vendor/winapi-0.2.8/src/wingdi.rs | 1238 -- vendor/winapi-0.2.8/src/winhttp.rs | 441 - vendor/winapi-0.2.8/src/winioctl.rs | 754 -- vendor/winapi-0.2.8/src/winnetwk.rs | 275 - vendor/winapi-0.2.8/src/winnls.rs | 164 - vendor/winapi-0.2.8/src/winnt.rs | 2368 ---- vendor/winapi-0.2.8/src/winreg.rs | 41 - vendor/winapi-0.2.8/src/winscard.rs | 269 - vendor/winapi-0.2.8/src/winsmcrd.rs | 157 - vendor/winapi-0.2.8/src/winsock2.rs | 429 - vendor/winapi-0.2.8/src/winspool.rs | 29 - vendor/winapi-0.2.8/src/winstring.rs | 3 - vendor/winapi-0.2.8/src/winsvc.rs | 200 - vendor/winapi-0.2.8/src/winusb.rs | 33 - vendor/winapi-0.2.8/src/winusbio.rs | 18 - vendor/winapi-0.2.8/src/winuser.rs | 2334 ---- vendor/winapi-0.2.8/src/ws2def.rs | 279 - vendor/winapi-0.2.8/src/ws2ipdef.rs | 42 - vendor/winapi-0.2.8/src/ws2spi.rs | 57 - vendor/winapi-0.2.8/src/ws2tcpip.rs | 27 - vendor/winapi-0.2.8/src/wtypes.rs | 75 - vendor/winapi-0.2.8/src/wtypesbase.rs | 37 - vendor/winapi-0.2.8/src/xinput.rs | 118 - vendor/winapi-build/.cargo-checksum.json | 1 - vendor/winapi-build/Cargo.toml | 11 - vendor/winapi-build/src/lib.rs | 14 - version | 2 +- 6099 files changed, 125847 insertions(+), 156396 deletions(-) create mode 100644 src/doc/book/.cargo/config create mode 100644 src/doc/book/ADMIN_TASKS.md create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml create mode 100644 src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt create mode 100644 src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-01/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-02/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-03/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-04/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-05/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-06/output.txt create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-06/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-07/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/listing-04-09/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt create mode 100644 src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt create mode 100644 src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml create mode 100644 src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/output.txt create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/output.txt create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs create mode 100644 src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-01/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-02/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-03/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-04/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-05/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-06/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-07/output.txt create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-07/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-08/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-09/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-10/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-11/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-12/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-13/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-14/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-15/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-16/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-17/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-18/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-19/output.txt create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-19/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-20/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-21/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-22/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-23/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-24/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-25/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/listing-08-26/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-02-format/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs create mode 100644 src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock create mode 100644 src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml create mode 100644 src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt create mode 100644 src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-01/output.txt create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-01/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-03/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-04/output.txt create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-04/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-05/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-06/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-07/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-08/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-09/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/listing-09-10/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-01-panic/output.txt create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-01-panic/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-03-closures/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-05-expect/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml create mode 100644 src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml create mode 100644 src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs create mode 100644 src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-01/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-01/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-02/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-02/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-03/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-03/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-04/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-04/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-04/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-05/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-05/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-06/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-06/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-07/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-07/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-07/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-08/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-08/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-08/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-09/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-09/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-10/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-10/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-10/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-11/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-11/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-12/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-12/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-12/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-13/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-13/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-13/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-14/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-14/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-14/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-15/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-15/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-15/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-16/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-16/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-16/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-17/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-17/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-17/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-18/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-18/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-18/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-19/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-19/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-19/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-19/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-20/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-20/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-20/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-21/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-21/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-21/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-21/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-22/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-22/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-22/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-23/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-23/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-23/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-23/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-24/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-24/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/listing-12-24/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/output.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs create mode 100644 src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-01/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-02/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-03/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-04/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-05/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-06/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-07/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-08/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-09/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-10/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-11/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-12/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-13/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-14/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-15/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-16/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-17/output.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-17/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-18/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-19/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-20/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-21/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-22/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-23/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-25/poem.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-25/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-25/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-26/poem.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-26/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-26/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-27/poem.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-27/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-27/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-29/poem.txt create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-29/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/listing-13-29/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/output.txt create mode 100644 src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml create mode 100644 src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-01/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-02/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-03/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-05/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-06/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-07/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-08/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-09/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-09/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-10/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-11/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-12/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-13/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-14/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-14/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-15/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-15/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-16/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-16/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-17/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-17/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-18/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-19/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-19/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-20/src/lib.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-21/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-21/src/lib.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-22/src/lib.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-23/src/lib.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-24/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-24/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-25/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-26/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-26/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-27/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-28/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/listing-15-29/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs create mode 100644 src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock create mode 100644 src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml create mode 100644 src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt create mode 100644 src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/output.txt create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/output.txt create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt create mode 100644 src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-01/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-01/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-01/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-02/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-02/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-02/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-03/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-03/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-03/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-04/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-04/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-04/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-05/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-05/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-05/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-06/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-06/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-06/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-07/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-07/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-07/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-08/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-08/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-08/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-08/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-09/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-09/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-09/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-09/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-10/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-10/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-10/output.txt create mode 100644 src/doc/book/listings/ch17-oop/listing-17-10/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-10/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-11/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-11/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-11/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-12/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-12/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-12/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-12/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-13/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-13/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-13/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-13/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-14/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-14/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-14/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-14/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-15/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-15/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-15/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-15/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-16/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-16/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-16/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-16/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-17/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-17/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-17/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-17/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-18/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-18/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-18/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-18/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-19/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-19/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-19/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-20/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-20/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-20/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-21/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/listing-17-21/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/listing-17-21/src/lib.rs create mode 100644 src/doc/book/listings/ch17-oop/listing-17-21/src/main.rs create mode 100644 src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock create mode 100644 src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml create mode 100644 src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt create mode 100644 src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/output.txt create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/output.txt create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/output.txt create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/output.txt create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml create mode 100644 src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-01/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-02/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-03/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-04/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-05/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-05/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-06/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-07/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-08/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-09/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-10/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-11/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-12/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-13/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-14/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-15/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-16/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-17/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-18/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-18/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-19/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-19/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-20/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-21/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-21/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-22/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-23/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-24/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-25/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-27/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-28/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-30/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs create mode 100644 src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock create mode 100644 src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml create mode 100644 src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt create mode 100644 src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-01/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-02/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-03/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-04/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-04/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-05/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-06/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-07/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-07/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-08/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-08/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-08/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-09/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-09/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-09/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-10/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-10/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-10/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-11/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-11/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-11/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-12/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-12/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-12/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-12/src/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-13/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-13/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-13/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-13/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-14/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-14/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-14/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-14/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-15/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-15/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-15/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-15/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-16/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-16/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-16/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-16/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-17/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-18/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-18/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-18/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-18/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-19/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-19/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-19/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-19/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-20/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-20/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-20/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-20/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-21/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-21/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-21/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-21/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-22/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-23/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-23/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-23/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-23/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-24/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-24/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-24/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-24/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-25/404.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-25/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-25/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/listing-20-25/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/404.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs create mode 100644 src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs create mode 100644 src/doc/book/rustfmt.toml create mode 100644 src/doc/book/tools/src/bin/release_listings.rs create mode 100644 src/doc/book/tools/src/bin/remove_hidden_lines.rs create mode 100755 src/doc/book/tools/update-rustc.sh create mode 100644 src/doc/embedded-book/src/appendix/glossary.md create mode 100644 src/doc/nomicon/book.toml rename src/doc/{rustc-guide => rustc-dev-guide}/.editorconfig (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/.travis.yml (89%) create mode 100644 src/doc/rustc-dev-guide/CNAME rename src/doc/{rustc-guide => rustc-dev-guide}/CODE_OF_CONDUCT.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/LICENSE-APACHE (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/LICENSE-MIT (100%) create mode 100644 src/doc/rustc-dev-guide/README.md create mode 100644 src/doc/rustc-dev-guide/book.toml rename src/doc/{rustc-guide => rustc-dev-guide}/ci/check_line_lengths.sh (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/SUMMARY.md (96%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/about-this-guide.md (95%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/appendix/background.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/appendix/bibliography.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/appendix/code-index.md (86%) create mode 100644 src/doc/rustc-dev-guide/src/appendix/compiler-lecture.md create mode 100644 src/doc/rustc-dev-guide/src/appendix/glossary.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/appendix/humorust.md (80%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/appendix/stupid-stats.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/moves_and_initialization.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/moves_and_initialization/move_paths.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference/closure_constraints.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference/constraint_propagation.md (97%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference/error_reporting.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference/lifetime_parameters.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference/member_constraints.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/region_inference/placeholders_and_universes.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/two_phase_borrows.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/borrow_check/type_check.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/bug-fix-procedure.md (99%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/building/bootstrapping.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/building/build-install-distribution-artifacts.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/building/compiler-documenting.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/building/ctags.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/building/how-to-build-and-run.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/building/suggested.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/closure.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/codegen.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/codegen/backend-agnostic.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/codegen/debugging.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/codegen/updating-llvm.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/compiler-debugging.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/compiler-team.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/compiletest.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/const-eval.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/conventions.md (99%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/crates-io.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/debugging-support-in-rustc.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/diagnostics.md (97%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/diagnostics/diagnostic-codes.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/diagnostics/lintstore.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/generic_arguments.md (100%) create mode 100644 src/doc/rustc-dev-guide/src/generics.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/high-level-overview.md (97%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/hir-debugging.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/hir.md (98%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/ice-breaker/about.md (94%) create mode 100644 src/doc/rustc-dev-guide/src/ice-breaker/cleanup-crew.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/ice-breaker/llvm.md (93%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/img/rustc_stages.svg (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/implementing_new_features.md (95%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/incrcomp-debugging.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/lowering.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/macro-expansion.md (96%) create mode 100644 src/doc/rustc-dev-guide/src/memory.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/method-lookup.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/construction.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/debugging.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/index.md (87%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/mir_detailed.dot (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/mir_detailed.svg (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/mir_overview.dot (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/mir_overview.svg (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/optimizations.md (84%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/passes.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/mir/visitor.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/miri.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/name-resolution.md (86%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/opaque-types-type-alias-impl-trait.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/panic-implementation.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/param_env.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/part-1-intro.md (78%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/part-2-intro.md (85%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/profile-guided-optimization.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/profiling.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/profiling/with_perf.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/example-0.counts.txt (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/example-0.html (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/example-0.png (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/incremental-compilation-in-detail.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/incremental-compilation.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/profiling.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/queries/query-evaluation-model-in-detail.md (99%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/query.md (82%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/rustc-driver.md (80%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/rustdoc.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/salsa.md (100%) create mode 100644 src/doc/rustc-dev-guide/src/sanitizers.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/stability.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/stabilization_guide.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/test-implementation.md (90%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/tests/adding.md (95%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/tests/intro.md (95%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/tests/running.md (89%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/the-parser.md (86%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/associated-types.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/bibliography.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/caching.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/canonical-queries.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/canonicalization.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/chalk-overview.md (99%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/goals-and-clauses.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/hrtb.md (97%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/implied-bounds.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/index.md (100%) create mode 100644 src/doc/rustc-dev-guide/src/traits/lowering-module.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/lowering-rules.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/lowering-to-logic.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/regions.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/resolution.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/slg.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/specialization.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/traits/wf.md (100%) create mode 100644 src/doc/rustc-dev-guide/src/ty-fold.md create mode 100644 src/doc/rustc-dev-guide/src/ty.md rename src/doc/{rustc-guide => rustc-dev-guide}/src/type-checking.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/type-inference.md (97%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/variance.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/src/walkthrough.md (100%) rename src/doc/{rustc-guide => rustc-dev-guide}/triagebot.toml (100%) delete mode 100644 src/doc/rustc-guide/README.md delete mode 100644 src/doc/rustc-guide/book.toml delete mode 100755 src/doc/rustc-guide/ci/install.sh delete mode 100644 src/doc/rustc-guide/src/appendix/compiler-lecture.md delete mode 100644 src/doc/rustc-guide/src/appendix/glossary.md delete mode 100644 src/doc/rustc-guide/src/sanitizers.md delete mode 100644 src/doc/rustc-guide/src/traits/lowering-module.md delete mode 100644 src/doc/rustc-guide/src/ty.md create mode 100644 src/doc/rustdoc/book.toml create mode 100644 src/doc/unstable-book/src/compiler-flags/control-flow-guard.md create mode 100644 src/doc/unstable-book/src/compiler-flags/self-profile-events.md create mode 100644 src/doc/unstable-book/src/compiler-flags/self-profile.md create mode 100644 src/doc/unstable-book/src/language-features/const-eval-limit.md delete mode 100644 src/doc/unstable-book/src/language-features/doc-spotlight.md create mode 100644 src/doc/unstable-book/src/language-features/link-cfg.md create mode 100644 src/doc/unstable-book/src/language-features/no-sanitize.md delete mode 100644 src/doc/unstable-book/src/library-features/read-initializer.md create mode 100644 src/doc/unstable-book/src/library-features/tidy-test-never-used-anywhere-else.md create mode 100644 src/liballoc/collections/btree/navigate.rs create mode 100644 src/liballoc/collections/vec_deque/drain.rs delete mode 100644 src/libcore/num/uint_macros.rs create mode 100644 src/libcore/primitive.rs delete mode 100644 src/librustc/hir/check_attr.rs create mode 100644 src/librustc/infer/canonical.rs delete mode 100644 src/librustc/infer/canonical/mod.rs delete mode 100644 src/librustc/infer/error_reporting/mod.rs delete mode 100644 src/librustc/infer/error_reporting/nice_region_error/mod.rs delete mode 100644 src/librustc/infer/error_reporting/nice_region_error/util.rs delete mode 100644 src/librustc/infer/higher_ranked/mod.rs delete mode 100644 src/librustc/infer/lexical_region_resolve/mod.rs delete mode 100644 src/librustc/infer/nll_relate/mod.rs delete mode 100644 src/librustc/infer/opaque_types/mod.rs delete mode 100644 src/librustc/infer/region_constraints/mod.rs create mode 100644 src/librustc/middle/limits.rs delete mode 100644 src/librustc/middle/recursion_limit.rs delete mode 100644 src/librustc/middle/weak_lang_items.rs delete mode 100644 src/librustc/traits/chalk_fulfill.rs delete mode 100644 src/librustc/traits/codegen/mod.rs delete mode 100644 src/librustc/traits/error_reporting/mod.rs delete mode 100644 src/librustc/traits/error_reporting/on_unimplemented.rs delete mode 100644 src/librustc/traits/misc.rs delete mode 100644 src/librustc/traits/object_safety.rs delete mode 100644 src/librustc/traits/on_unimplemented.rs create mode 100644 src/librustc/traits/query.rs delete mode 100644 src/librustc/traits/query/dropck_outlives.rs delete mode 100644 src/librustc/traits/query/method_autoderef.rs delete mode 100644 src/librustc/traits/query/mod.rs delete mode 100644 src/librustc/traits/query/normalize.rs delete mode 100644 src/librustc/traits/query/outlives_bounds.rs delete mode 100644 src/librustc/traits/query/type_op/ascribe_user_type.rs delete mode 100644 src/librustc/traits/query/type_op/eq.rs delete mode 100644 src/librustc/traits/query/type_op/mod.rs delete mode 100644 src/librustc/traits/query/type_op/normalize.rs delete mode 100644 src/librustc/traits/query/type_op/subtype.rs create mode 100644 src/librustc/traits/specialization_graph.rs delete mode 100644 src/librustc/traits/specialize/mod.rs delete mode 100644 src/librustc/traits/specialize/specialization_graph.rs delete mode 100644 src/librustc/traits/util.rs create mode 100644 src/librustc/ty/query/caches.rs create mode 100644 src/librustc/ty/query/stats.rs create mode 100644 src/librustc_ast/Cargo.toml create mode 100644 src/librustc_ast/README.md rename src/{libsyntax => librustc_ast}/ast.rs (92%) rename src/{libsyntax => librustc_ast}/ast/tests.rs (100%) create mode 100644 src/librustc_ast/attr/mod.rs rename src/{libsyntax => librustc_ast}/build.rs (100%) rename src/{libsyntax => librustc_ast}/entry.rs (100%) rename src/{libsyntax => librustc_ast}/expand/allocator.rs (100%) rename src/{libsyntax => librustc_ast}/expand/mod.rs (100%) create mode 100644 src/librustc_ast/lib.rs rename src/{libsyntax => librustc_ast}/mut_visit.rs (94%) create mode 100644 src/librustc_ast/node_id.rs rename src/{libsyntax => librustc_ast}/ptr.rs (100%) rename src/{libsyntax => librustc_ast}/token.rs (78%) rename src/{libsyntax => librustc_ast}/tokenstream.rs (98%) rename src/{libsyntax => librustc_ast}/util/classify.rs (100%) rename src/{libsyntax => librustc_ast}/util/comments.rs (97%) rename src/{libsyntax => librustc_ast}/util/comments/tests.rs (100%) rename src/{libsyntax => librustc_ast}/util/lev_distance.rs (100%) rename src/{libsyntax => librustc_ast}/util/lev_distance/tests.rs (100%) rename src/{libsyntax => librustc_ast}/util/literal.rs (98%) rename src/{libsyntax => librustc_ast}/util/map_in_place.rs (100%) rename src/{libsyntax => librustc_ast}/util/parser.rs (99%) rename src/{libsyntax => librustc_ast}/visit.rs (87%) rename src/{libsyntax/util => librustc_ast_passes}/node_count.rs (93%) create mode 100644 src/librustc_ast_pretty/Cargo.toml rename src/{libsyntax/print => librustc_ast_pretty}/helpers.rs (95%) create mode 100644 src/librustc_ast_pretty/lib.rs rename src/{libsyntax/print => librustc_ast_pretty}/pp.rs (100%) rename src/{libsyntax/print => librustc_ast_pretty}/pprust.rs (89%) rename src/{libsyntax/print => librustc_ast_pretty}/pprust/tests.rs (75%) create mode 100644 src/librustc_attr/Cargo.toml create mode 100644 src/librustc_attr/builtin.rs create mode 100644 src/librustc_attr/lib.rs create mode 100644 src/librustc_codegen_llvm/back/profiling.rs create mode 100644 src/librustc_codegen_ssa/build.rs create mode 100644 src/librustc_data_structures/sorted_map/index_map.rs create mode 100644 src/librustc_error_codes/error_codes/E0637.md create mode 100644 src/librustc_error_codes/error_codes/E0719.md create mode 100644 src/librustc_error_codes/error_codes/E0727.md create mode 100644 src/librustc_error_codes/error_codes/E0747.md create mode 100644 src/librustc_error_codes/error_codes/E0748.md create mode 100644 src/librustc_hir/lang_items.rs create mode 100644 src/librustc_hir/target.rs create mode 100644 src/librustc_hir/weak_lang_items.rs create mode 100644 src/librustc_infer/Cargo.toml rename src/{librustc => librustc_infer}/infer/at.rs (98%) rename src/{librustc => librustc_infer}/infer/canonical/canonicalizer.rs (95%) create mode 100644 src/librustc_infer/infer/canonical/mod.rs rename src/{librustc => librustc_infer}/infer/canonical/query_response.rs (89%) rename src/{librustc => librustc_infer}/infer/canonical/substitute.rs (78%) rename src/{librustc => librustc_infer}/infer/combine.rs (92%) rename src/{librustc => librustc_infer}/infer/equate.rs (76%) create mode 100644 src/librustc_infer/infer/error_reporting/mod.rs rename src/{librustc => librustc_infer}/infer/error_reporting/need_type_info.rs (96%) rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/different_lifetimes.rs (98%) rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/find_anon_type.rs (99%) create mode 100644 src/librustc_infer/infer/error_reporting/nice_region_error/mod.rs rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/named_anon_conflict.rs (96%) rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/outlives_closure.rs (98%) rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/placeholder_error.rs (95%) rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/static_impl_trait.rs (97%) rename src/{librustc => librustc_infer}/infer/error_reporting/nice_region_error/trait_impl_difference.rs (97%) create mode 100644 src/librustc_infer/infer/error_reporting/nice_region_error/util.rs rename src/{librustc => librustc_infer}/infer/error_reporting/note.rs (99%) rename src/{librustc => librustc_infer}/infer/freshen.rs (93%) rename src/{librustc => librustc_infer}/infer/fudge.rs (88%) rename src/{librustc => librustc_infer}/infer/glb.rs (90%) rename src/{librustc => librustc_infer}/infer/higher_ranked/README.md (100%) create mode 100644 src/librustc_infer/infer/higher_ranked/mod.rs rename src/{librustc => librustc_infer}/infer/lattice.rs (93%) rename src/{librustc => librustc_infer}/infer/lexical_region_resolve/README.md (100%) rename src/{librustc => librustc_infer}/infer/lexical_region_resolve/graphviz.rs (98%) create mode 100644 src/librustc_infer/infer/lexical_region_resolve/mod.rs rename src/{librustc => librustc_infer}/infer/lub.rs (90%) create mode 100644 src/librustc_infer/infer/mod.rs create mode 100644 src/librustc_infer/infer/nll_relate/mod.rs create mode 100644 src/librustc_infer/infer/opaque_types/mod.rs rename src/{librustc => librustc_infer}/infer/outlives/env.rs (99%) rename src/{librustc => librustc_infer}/infer/outlives/mod.rs (100%) rename src/{librustc => librustc_infer}/infer/outlives/obligations.rs (98%) rename src/{librustc => librustc_infer}/infer/outlives/verify.rs (94%) rename src/{librustc => librustc_infer}/infer/region_constraints/README.md (100%) rename src/{librustc => librustc_infer}/infer/region_constraints/leak_check.rs (87%) create mode 100644 src/librustc_infer/infer/region_constraints/mod.rs rename src/{librustc => librustc_infer}/infer/resolve.rs (93%) rename src/{librustc => librustc_infer}/infer/sub.rs (89%) rename src/{librustc => librustc_infer}/infer/type_variable.rs (97%) create mode 100644 src/librustc_infer/lib.rs rename src/{librustc => librustc_infer}/traits/auto_trait.rs (98%) create mode 100644 src/librustc_infer/traits/codegen/mod.rs rename src/{librustc => librustc_infer}/traits/coherence.rs (92%) rename src/{librustc => librustc_infer}/traits/engine.rs (86%) create mode 100644 src/librustc_infer/traits/error_reporting/mod.rs create mode 100644 src/librustc_infer/traits/error_reporting/on_unimplemented.rs rename src/{librustc => librustc_infer}/traits/error_reporting/suggestions.rs (94%) rename src/{librustc => librustc_infer}/traits/fulfill.rs (92%) create mode 100644 src/librustc_infer/traits/misc.rs create mode 100644 src/librustc_infer/traits/mod.rs create mode 100644 src/librustc_infer/traits/object_safety.rs create mode 100644 src/librustc_infer/traits/on_unimplemented.rs rename src/{librustc => librustc_infer}/traits/project.rs (92%) create mode 100644 src/librustc_infer/traits/query/dropck_outlives.rs rename src/{librustc => librustc_infer}/traits/query/evaluate_obligation.rs (100%) create mode 100644 src/librustc_infer/traits/query/method_autoderef.rs create mode 100644 src/librustc_infer/traits/query/mod.rs create mode 100644 src/librustc_infer/traits/query/normalize.rs create mode 100644 src/librustc_infer/traits/query/outlives_bounds.rs create mode 100644 src/librustc_infer/traits/query/type_op/ascribe_user_type.rs rename src/{librustc => librustc_infer}/traits/query/type_op/custom.rs (100%) create mode 100644 src/librustc_infer/traits/query/type_op/eq.rs rename src/{librustc => librustc_infer}/traits/query/type_op/implied_outlives_bounds.rs (96%) create mode 100644 src/librustc_infer/traits/query/type_op/mod.rs create mode 100644 src/librustc_infer/traits/query/type_op/normalize.rs rename src/{librustc => librustc_infer}/traits/query/type_op/outlives.rs (97%) rename src/{librustc => librustc_infer}/traits/query/type_op/prove_predicate.rs (78%) create mode 100644 src/librustc_infer/traits/query/type_op/subtype.rs create mode 100644 src/librustc_infer/traits/select.rs create mode 100644 src/librustc_infer/traits/specialize/mod.rs create mode 100644 src/librustc_infer/traits/specialize/specialization_graph.rs create mode 100644 src/librustc_infer/traits/structural_impls.rs rename src/{librustc => librustc_infer}/traits/structural_match.rs (97%) create mode 100644 src/librustc_infer/traits/util.rs rename src/{librustc => librustc_infer}/traits/wf.rs (96%) delete mode 100644 src/librustc_mir/borrow_check/flows.rs create mode 100644 src/librustc_mir/borrow_check/region_infer/opaque_types.rs create mode 100644 src/librustc_mir/borrow_check/region_infer/reverse_sccs.rs delete mode 100644 src/librustc_mir/const_eval.rs create mode 100644 src/librustc_mir/const_eval/mod.rs create mode 100644 src/librustc_mir/dataflow/generic/visitor.rs delete mode 100644 src/librustc_mir/dataflow/impls/indirect_mutation.rs create mode 100644 src/librustc_passes/check_attr.rs create mode 100644 src/librustc_passes/lang_items.rs rename src/{librustc/hir => librustc_passes}/upvars.rs (97%) create mode 100644 src/librustc_passes/weak_lang_items.rs rename src/librustc_resolve/{ => late}/lifetimes.rs (95%) delete mode 100644 src/librustc_session/node_id.rs rename src/{librustc_hir => librustc_span}/def_id.rs (95%) delete mode 100644 src/librustc_traits/chalk_context/mod.rs delete mode 100644 src/librustc_traits/chalk_context/program_clauses/builtin.rs delete mode 100644 src/librustc_traits/chalk_context/program_clauses/mod.rs delete mode 100644 src/librustc_traits/chalk_context/program_clauses/primitive.rs delete mode 100644 src/librustc_traits/chalk_context/resolvent_ops.rs delete mode 100644 src/librustc_traits/chalk_context/unify.rs delete mode 100644 src/librustc_traits/generic_types.rs create mode 100644 src/librustc_ty/common_traits.rs create mode 100644 src/librustc_ty/instance.rs create mode 100644 src/librustc_ty/needs_drop.rs create mode 100644 src/librustc_typeck/collect/type_of.rs delete mode 100644 src/librustc_typeck/namespace.rs delete mode 100644 src/libsyntax/Cargo.toml delete mode 100644 src/libsyntax/README.md delete mode 100644 src/libsyntax/attr/builtin.rs delete mode 100644 src/libsyntax/attr/mod.rs delete mode 100644 src/libsyntax/lib.rs create mode 100644 src/stdarch/.github/workflows/main.yml delete mode 100644 src/stdarch/QUESTIONS.md delete mode 100644 src/stdarch/ci/azure-install-rust.yml delete mode 100644 src/stdarch/ci/azure.yml mode change 100644 => 100755 src/stdarch/ci/style.sh create mode 100644 src/stdarch/crates/core_arch/rustfmt.toml create mode 100644 src/stdarch/crates/std_detect/src/detect/macros.rs create mode 100644 src/stdarch/crates/std_detect/src/detect/os/windows/aarch64.rs create mode 100644 src/stdarch/crates/std_detect/tests/x86-specific.rs create mode 100644 src/test/codegen/cfguard_checks.rs create mode 100644 src/test/codegen/cfguard_disabled.rs create mode 100644 src/test/codegen/cfguard_nochecks.rs create mode 100644 src/test/codegen/enum-discriminant-value.rs create mode 100644 src/test/codegen/riscv-abi/riscv64-lp64-lp64f-lp64d-abi.rs create mode 100644 src/test/codegen/riscv-abi/riscv64-lp64d-abi.rs create mode 100644 src/test/codegen/riscv-abi/riscv64-lp64f-lp64d-abi.rs create mode 100644 src/test/codegen/sanitizer-no-sanitize-inlining.rs create mode 100644 src/test/codegen/sanitizer-no-sanitize.rs delete mode 100644 src/test/compile-fail/chalkify/chalk_initial_program.rs delete mode 100644 src/test/compile-fail/chalkify/generic_impls.rs delete mode 100644 src/test/compile-fail/chalkify/impl_wf.rs delete mode 100644 src/test/compile-fail/chalkify/recursive_where_clause_on_type.rs delete mode 100644 src/test/compile-fail/chalkify/type_wf.rs delete mode 100644 src/test/compile-fail/consts/const-err3.rs delete mode 100644 src/test/debuginfo/no-debug-attribute.rs create mode 100644 src/test/incremental/const-generics/issue-68477.rs create mode 100644 src/test/incremental/issue-62649-path-collisions-happen.rs create mode 100644 src/test/incremental/thinlto/cgu_invalidated_when_export_added.rs create mode 100644 src/test/incremental/thinlto/cgu_invalidated_when_export_removed.rs create mode 100644 src/test/mir-opt/exponential-or.rs create mode 100644 src/test/pretty/gat-bounds.rs create mode 100644 src/test/pretty/if-attr.rs create mode 100644 src/test/pretty/issue-68710-field-attr-proc-mac-lost.rs create mode 100644 src/test/pretty/nested-item-vis-defaultness.rs create mode 100644 src/test/pretty/trait-inner-attr.rs create mode 100644 src/test/run-make-fulldeps/arguments-non-c-like-enum/Makefile create mode 100644 src/test/run-make-fulldeps/arguments-non-c-like-enum/nonclike.rs create mode 100644 src/test/run-make-fulldeps/arguments-non-c-like-enum/test.c create mode 100644 src/test/run-make-fulldeps/issue-69368/Makefile create mode 100644 src/test/run-make-fulldeps/issue-69368/a.rs create mode 100644 src/test/run-make-fulldeps/issue-69368/b.rs create mode 100644 src/test/run-make-fulldeps/issue-69368/c.rs create mode 100644 src/test/run-make-fulldeps/pass-non-c-like-enum-to-c/Makefile create mode 100644 src/test/run-make-fulldeps/pass-non-c-like-enum-to-c/nonclike.rs create mode 100644 src/test/run-make-fulldeps/pass-non-c-like-enum-to-c/test.c create mode 100644 src/test/run-make-fulldeps/return-non-c-like-enum-from-c/Makefile create mode 100644 src/test/run-make-fulldeps/return-non-c-like-enum-from-c/nonclike.rs create mode 100644 src/test/run-make-fulldeps/return-non-c-like-enum-from-c/test.c create mode 100644 src/test/run-make-fulldeps/return-non-c-like-enum/Makefile create mode 100644 src/test/run-make-fulldeps/return-non-c-like-enum/nonclike.rs create mode 100644 src/test/run-make-fulldeps/return-non-c-like-enum/test.c create mode 100644 src/test/rustdoc-js/struct-like-variant.js create mode 100644 src/test/rustdoc-js/struct-like-variant.rs create mode 100644 src/test/rustdoc/auxiliary/primitive-reexport.rs create mode 100644 src/test/rustdoc/crate-version-escape.rs delete mode 100644 src/test/rustdoc/doc-spotlight.rs create mode 100644 src/test/rustdoc/primitive-reexport.rs create mode 100644 src/test/ui-fulldeps/lint-group-denied-lint-allowed.rs delete mode 100644 src/test/ui/allocator-alloc-one.rs create mode 100644 src/test/ui/asm/issue-62046.rs create mode 100644 src/test/ui/asm/issue-62046.stderr delete mode 100644 src/test/ui/assign-to-method.rs delete mode 100644 src/test/ui/assign-to-method.stderr create mode 100644 src/test/ui/associated-const/defaults-cyclic-fail.rs create mode 100644 src/test/ui/associated-const/defaults-cyclic-fail.stderr create mode 100644 src/test/ui/associated-const/defaults-cyclic-pass.rs create mode 100644 src/test/ui/associated-const/defaults-not-assumed-fail.rs create mode 100644 src/test/ui/associated-const/defaults-not-assumed-fail.stderr create mode 100644 src/test/ui/associated-const/defaults-not-assumed-pass.rs create mode 100644 src/test/ui/associated-item/associated-item-duplicate-bounds.rs create mode 100644 src/test/ui/associated-item/associated-item-duplicate-bounds.stderr delete mode 100644 src/test/ui/associated-types/associated-types-overridden-default.stderr create mode 100644 src/test/ui/associated-types/associated-types-project-from-hrtb-in-fn.fixed create mode 100644 src/test/ui/associated-types/associated-types-project-from-hrtb-in-trait-method.fixed create mode 100644 src/test/ui/associated-types/defaults-cyclic-fail-1.rs create mode 100644 src/test/ui/associated-types/defaults-cyclic-fail-1.stderr create mode 100644 src/test/ui/associated-types/defaults-cyclic-fail-2.rs create mode 100644 src/test/ui/associated-types/defaults-cyclic-fail-2.stderr create mode 100644 src/test/ui/associated-types/defaults-cyclic-pass-1.rs create mode 100644 src/test/ui/associated-types/defaults-cyclic-pass-2.rs create mode 100644 src/test/ui/associated-types/defaults-in-other-trait-items-pass.rs create mode 100644 src/test/ui/associated-types/defaults-in-other-trait-items.rs create mode 100644 src/test/ui/associated-types/defaults-in-other-trait-items.stderr create mode 100644 src/test/ui/associated-types/defaults-mixed.rs create mode 100644 src/test/ui/associated-types/defaults-mixed.stderr create mode 100644 src/test/ui/associated-types/defaults-specialization.rs create mode 100644 src/test/ui/associated-types/defaults-specialization.stderr create mode 100644 src/test/ui/associated-types/defaults-suitability.rs create mode 100644 src/test/ui/associated-types/defaults-suitability.stderr create mode 100644 src/test/ui/associated-types/defaults-unsound-62211-1.rs create mode 100644 src/test/ui/associated-types/defaults-unsound-62211-1.stderr create mode 100644 src/test/ui/associated-types/defaults-unsound-62211-2.rs create mode 100644 src/test/ui/associated-types/defaults-unsound-62211-2.stderr create mode 100644 src/test/ui/associated-types/issue-26681.rs create mode 100644 src/test/ui/associated-types/issue-26681.stderr create mode 100644 src/test/ui/associated-types/issue-32350.rs create mode 100644 src/test/ui/associated-types/issue-41868.rs create mode 100644 src/test/ui/associated-types/issue-43924.rs create mode 100644 src/test/ui/associated-types/issue-43924.stderr create mode 100644 src/test/ui/associated-types/issue-47385.rs create mode 100644 src/test/ui/associated-types/issue-54182-1.rs create mode 100644 src/test/ui/associated-types/issue-54182-2.rs create mode 100644 src/test/ui/associated-types/issue-63593.rs create mode 100644 src/test/ui/associated-types/issue-63593.stderr create mode 100644 src/test/ui/associated-types/issue-65774-1.rs create mode 100644 src/test/ui/associated-types/issue-65774-1.stderr create mode 100644 src/test/ui/associated-types/issue-65774-2.rs create mode 100644 src/test/ui/associated-types/issue-65774-2.stderr create mode 100644 src/test/ui/async-await/issue-54239-private-type-triggers-lint.rs delete mode 100644 src/test/ui/bind-by-move/bind-by-move-neither-can-live-while-the-other-survives-2.rs delete mode 100644 src/test/ui/bind-by-move/bind-by-move-neither-can-live-while-the-other-survives-2.stderr delete mode 100644 src/test/ui/bind-by-move/bind-by-move-neither-can-live-while-the-other-survives-3.rs delete mode 100644 src/test/ui/bind-by-move/bind-by-move-neither-can-live-while-the-other-survives-3.stderr delete mode 100644 src/test/ui/bind-by-move/bind-by-move-neither-can-live-while-the-other-survives-4.rs delete mode 100644 src/test/ui/bind-by-move/bind-by-move-neither-can-live-while-the-other-survives-4.stderr create mode 100644 src/test/ui/borrowck/bindings-after-at-or-patterns-slice-patterns-box-patterns.rs create mode 100644 src/test/ui/borrowck/bindings-after-at-or-patterns-slice-patterns-box-patterns.stderr create mode 100644 src/test/ui/borrowck/borrow-immutable-upvar-mutation-impl-trait.rs create mode 100644 src/test/ui/borrowck/borrow-immutable-upvar-mutation-impl-trait.stderr create mode 100644 src/test/ui/borrowck/or-patterns.rs create mode 100644 src/test/ui/borrowck/or-patterns.stderr create mode 100644 src/test/ui/bound-suggestions.fixed create mode 100644 src/test/ui/bound-suggestions.rs create mode 100644 src/test/ui/bound-suggestions.stderr delete mode 100644 src/test/ui/chalkify/builtin-copy-clone.rs delete mode 100644 src/test/ui/chalkify/inherent_impl.rs delete mode 100644 src/test/ui/chalkify/lower_env1.rs delete mode 100644 src/test/ui/chalkify/lower_env1.stderr delete mode 100644 src/test/ui/chalkify/lower_env2.rs delete mode 100644 src/test/ui/chalkify/lower_env2.stderr delete mode 100644 src/test/ui/chalkify/lower_env3.rs delete mode 100644 src/test/ui/chalkify/lower_env3.stderr delete mode 100644 src/test/ui/chalkify/lower_impl.rs delete mode 100644 src/test/ui/chalkify/lower_impl.stderr delete mode 100644 src/test/ui/chalkify/lower_struct.rs delete mode 100644 src/test/ui/chalkify/lower_struct.stderr delete mode 100644 src/test/ui/chalkify/lower_trait.rs delete mode 100644 src/test/ui/chalkify/lower_trait.stderr delete mode 100644 src/test/ui/chalkify/lower_trait_higher_rank.rs delete mode 100644 src/test/ui/chalkify/lower_trait_higher_rank.stderr delete mode 100644 src/test/ui/chalkify/lower_trait_where_clause.rs delete mode 100644 src/test/ui/chalkify/lower_trait_where_clause.stderr delete mode 100644 src/test/ui/chalkify/projection.rs delete mode 100644 src/test/ui/chalkify/super_trait.rs delete mode 100644 src/test/ui/chalkify/trait_implied_bound.rs delete mode 100644 src/test/ui/chalkify/type_implied_bound.rs delete mode 100644 src/test/ui/chalkify/type_inference.rs delete mode 100644 src/test/ui/chalkify/type_inference.stderr create mode 100644 src/test/ui/closures/deeply-nested_closures.rs create mode 100644 src/test/ui/coherence/coherence-inherited-subtyping.old.stderr create mode 100644 src/test/ui/coherence/coherence-inherited-subtyping.re.stderr create mode 100644 src/test/ui/coherence/coherence-inherited-subtyping.rs create mode 100644 src/test/ui/coherence/coherence-subtyping.old.stderr create mode 100644 src/test/ui/coherence/coherence-subtyping.re.stderr create mode 100644 src/test/ui/const-generics/const-arg-type-arg-misordered.rs create mode 100644 src/test/ui/const-generics/const-arg-type-arg-misordered.stderr create mode 100644 src/test/ui/const-generics/const-param-after-const-literal-arg.rs delete mode 100644 src/test/ui/const-generics/issues/issue-65675.rs delete mode 100644 src/test/ui/const-generics/issues/issue-65675.stderr create mode 100644 src/test/ui/consts/ascii_ctype.rs create mode 100644 src/test/ui/consts/const-err2.noopt.stderr create mode 100644 src/test/ui/consts/const-err2.opt.stderr create mode 100644 src/test/ui/consts/const-err2.opt_with_overflow_checks.stderr delete mode 100644 src/test/ui/consts/const-err2.stderr delete mode 100644 src/test/ui/consts/const-err3.rs delete mode 100644 src/test/ui/consts/const-err3.stderr create mode 100644 src/test/ui/consts/const-eval/promoted_errors.noopt.stderr create mode 100644 src/test/ui/consts/const-eval/promoted_errors.opt.stderr create mode 100644 src/test/ui/consts/const-eval/promoted_errors.opt_with_overflow_checks.stderr delete mode 100644 src/test/ui/consts/const-eval/promoted_errors.stderr delete mode 100644 src/test/ui/consts/const-eval/promoted_errors2.rs delete mode 100644 src/test/ui/consts/const-eval/promoted_errors2.stderr create mode 100644 src/test/ui/consts/const-int-arithmetic-overflow.rs create mode 100644 src/test/ui/consts/const-int-arithmetic.rs create mode 100644 src/test/ui/consts/const_limit/const_eval_limit_not_reached.rs create mode 100644 src/test/ui/consts/const_limit/const_eval_limit_overflow.rs create mode 100644 src/test/ui/consts/const_limit/const_eval_limit_overflow.stderr create mode 100644 src/test/ui/consts/const_limit/const_eval_limit_reached.rs create mode 100644 src/test/ui/consts/const_limit/const_eval_limit_reached.stderr create mode 100644 src/test/ui/consts/const_limit/feature-gate-const_eval_limit.rs create mode 100644 src/test/ui/consts/const_limit/feature-gate-const_eval_limit.stderr create mode 100644 src/test/ui/consts/is_ascii.rs create mode 100644 src/test/ui/consts/issue-63952.rs create mode 100644 src/test/ui/consts/issue-63952.stderr delete mode 100644 src/test/ui/consts/issue-64059-2.rs create mode 100644 src/test/ui/consts/issue-68684.rs create mode 100644 src/test/ui/consts/issue-69020.noopt.stderr create mode 100644 src/test/ui/consts/issue-69020.opt.stderr create mode 100644 src/test/ui/consts/issue-69020.opt_with_overflow_checks.stderr create mode 100644 src/test/ui/consts/issue-69020.rs create mode 100644 src/test/ui/consts/issue-69312.rs create mode 100644 src/test/ui/consts/min_const_fn/min_const_fn_impl_trait.rs create mode 100644 src/test/ui/consts/min_const_fn/min_const_fn_impl_trait.stderr delete mode 100644 src/test/ui/consts/std/char.rs create mode 100644 src/test/ui/duplicate/dupe-symbols-8.rs create mode 100644 src/test/ui/duplicate/dupe-symbols-8.stderr delete mode 100644 src/test/ui/error-codes/E0009.rs delete mode 100644 src/test/ui/error-codes/E0009.stderr delete mode 100644 src/test/ui/feature-gates/feature-gate-doc_spotlight.rs delete mode 100644 src/test/ui/feature-gates/feature-gate-doc_spotlight.stderr delete mode 100644 src/test/ui/feature-gates/feature-gate-no-debug-2.rs delete mode 100644 src/test/ui/feature-gates/feature-gate-no-debug-2.stderr delete mode 100644 src/test/ui/feature-gates/feature-gate-no-debug.rs delete mode 100644 src/test/ui/feature-gates/feature-gate-no-debug.stderr create mode 100644 src/test/ui/feature-gates/feature-gate-no_sanitize.rs create mode 100644 src/test/ui/feature-gates/feature-gate-no_sanitize.stderr create mode 100644 src/test/ui/generator/dropck-resume.rs create mode 100644 src/test/ui/generator/dropck-resume.stderr create mode 100644 src/test/ui/generator/issue-64620-yield-array-element.rs create mode 100644 src/test/ui/generator/issue-64620-yield-array-element.stderr create mode 100644 src/test/ui/generator/issue-69017.rs create mode 100644 src/test/ui/generator/issue-69039.rs delete mode 100644 src/test/ui/generator/no-parameters-on-generators.rs delete mode 100644 src/test/ui/generator/no-parameters-on-generators.stderr create mode 100644 src/test/ui/generator/panic-drops-resume.rs create mode 100644 src/test/ui/generator/resume-arg-late-bound.rs create mode 100644 src/test/ui/generator/resume-arg-late-bound.stderr create mode 100644 src/test/ui/generator/resume-live-across-yield.rs create mode 100644 src/test/ui/generator/retain-resume-ref.rs create mode 100644 src/test/ui/generator/retain-resume-ref.stderr create mode 100644 src/test/ui/generator/smoke-resume-args.rs create mode 100644 src/test/ui/generator/too-many-parameters.rs create mode 100644 src/test/ui/generator/too-many-parameters.stderr create mode 100644 src/test/ui/generator/type-mismatch-error.rs create mode 100644 src/test/ui/generator/type-mismatch-error.stderr create mode 100644 src/test/ui/generic-associated-types/issue-68653.rs create mode 100644 src/test/ui/if-attrs/bad-cfg.rs create mode 100644 src/test/ui/if-attrs/bad-cfg.stderr create mode 100644 src/test/ui/if-attrs/builtin-if-attr.rs create mode 100644 src/test/ui/if-attrs/cfg-false-if-attr.rs create mode 100644 src/test/ui/if-attrs/else-attrs.rs create mode 100644 src/test/ui/if-attrs/else-attrs.stderr create mode 100644 src/test/ui/if-attrs/gate-whole-expr.rs create mode 100644 src/test/ui/if-attrs/let-chains-attr.rs create mode 100644 src/test/ui/if-attrs/let-chains-attr.stderr create mode 100644 src/test/ui/if-attrs/stmt-expr-gated.rs create mode 100644 src/test/ui/if-attrs/stmt-expr-gated.stderr create mode 100644 src/test/ui/impl-trait/equal-hidden-lifetimes.rs create mode 100644 src/test/ui/impl-trait/equal-hidden-lifetimes.stderr create mode 100644 src/test/ui/impl-trait/issue-57200.rs create mode 100644 src/test/ui/impl-trait/issue-57200.stderr create mode 100644 src/test/ui/impl-trait/issue-57201.rs create mode 100644 src/test/ui/impl-trait/issue-57201.stderr create mode 100644 src/test/ui/impl-trait/issue-60473.rs create mode 100644 src/test/ui/impl-trait/issue-60473.stderr create mode 100644 src/test/ui/impl-trait/issue-67166.rs create mode 100644 src/test/ui/impl-trait/issue-67166.stderr create mode 100644 src/test/ui/impl-trait/multiple-lifetimes/error-handling-2.rs create mode 100644 src/test/ui/impl-trait/multiple-lifetimes/error-handling-2.stderr create mode 100644 src/test/ui/impl-trait/nested-return-type.rs create mode 100644 src/test/ui/impl-trait/unsafety-checking-cycle.rs create mode 100644 src/test/ui/inference/infer-binary-operand-behind-reference.rs create mode 100644 src/test/ui/invalid/invalid-no-sanitize.rs create mode 100644 src/test/ui/invalid/invalid-no-sanitize.stderr create mode 100644 src/test/ui/issues/auxiliary/issue-51798.rs create mode 100644 src/test/ui/issues/auxiliary/issue-69725.rs delete mode 100644 src/test/ui/issues/issue-22933-3.rs delete mode 100644 src/test/ui/issues/issue-22933-3.stderr create mode 100644 src/test/ui/issues/issue-51798.rs delete mode 100644 src/test/ui/issues/issue-53840.rs delete mode 100644 src/test/ui/issues/issue-53840.stderr create mode 100644 src/test/ui/issues/issue-68696-catch-during-unwind.rs create mode 100644 src/test/ui/issues/issue-69306.rs create mode 100644 src/test/ui/issues/issue-69306.stderr create mode 100644 src/test/ui/issues/issue-69602-type-err-during-codegen-ice.rs create mode 100644 src/test/ui/issues/issue-69602-type-err-during-codegen-ice.stderr create mode 100644 src/test/ui/issues/issue-69725.rs create mode 100644 src/test/ui/issues/issue-69725.stderr create mode 100644 src/test/ui/issues/issue-8460-const.noopt.stderr create mode 100644 src/test/ui/issues/issue-8460-const.opt.stderr create mode 100644 src/test/ui/issues/issue-8460-const.opt_with_overflow_checks.stderr delete mode 100644 src/test/ui/issues/issue-8460-const.stderr delete mode 100644 src/test/ui/issues/issue-8460-const2.rs delete mode 100644 src/test/ui/issues/issue-8460-const2.stderr create mode 100644 src/test/ui/layout/unsafe-cell-hides-niche.rs create mode 100644 src/test/ui/lint/lint-exceeding-bitshifts.noopt.stderr create mode 100644 src/test/ui/lint/lint-exceeding-bitshifts.opt.stderr create mode 100644 src/test/ui/lint/lint-exceeding-bitshifts.opt_with_overflow_checks.stderr delete mode 100644 src/test/ui/lint/lint-exceeding-bitshifts.stderr delete mode 100644 src/test/ui/lint/lint-exceeding-bitshifts2.rs delete mode 100644 src/test/ui/lint/lint-exceeding-bitshifts2.stderr create mode 100644 src/test/ui/macro_backtrace/main.-Zmacro-backtrace.stderr create mode 100644 src/test/ui/macro_backtrace/main.default.stderr delete mode 100644 src/test/ui/macro_backtrace/main.stderr create mode 100644 src/test/ui/macros/issue-68060.rs create mode 100644 src/test/ui/macros/issue-68060.stderr create mode 100644 src/test/ui/macros/issue-70446.rs create mode 100644 src/test/ui/methods/assign-to-method.rs create mode 100644 src/test/ui/methods/assign-to-method.stderr create mode 100644 src/test/ui/mir/mir-inlining/var-debuginfo-issue-67586.rs delete mode 100644 src/test/ui/missing/missing-semicolon-warning.rs delete mode 100644 src/test/ui/missing/missing-semicolon-warning.stderr create mode 100644 src/test/ui/nll/user-annotations/type-annotation-with-hrtb.rs create mode 100644 src/test/ui/or-patterns/basic-switch.rs create mode 100644 src/test/ui/or-patterns/basic-switchint.rs create mode 100644 src/test/ui/or-patterns/bindings-runpass-1.rs create mode 100644 src/test/ui/or-patterns/bindings-runpass-2.rs create mode 100644 src/test/ui/or-patterns/box-patterns.rs delete mode 100644 src/test/ui/or-patterns/consistent-bindings.stderr delete mode 100644 src/test/ui/or-patterns/exhaustiveness-pass.stderr create mode 100644 src/test/ui/or-patterns/for-loop.rs create mode 100644 src/test/ui/or-patterns/if-let-while-let.rs create mode 100644 src/test/ui/or-patterns/issue-67514-irrefutable-param.rs create mode 100644 src/test/ui/or-patterns/issue-68785-irrefutable-param-with-at.rs create mode 100644 src/test/ui/or-patterns/let-pattern.rs create mode 100644 src/test/ui/or-patterns/mix-with-wild.rs delete mode 100644 src/test/ui/or-patterns/or-pattern-mismatch.rs delete mode 100644 src/test/ui/or-patterns/or-pattern-mismatch.stderr create mode 100644 src/test/ui/or-patterns/or-patterns-binding-type-mismatch.rs create mode 100644 src/test/ui/or-patterns/or-patterns-binding-type-mismatch.stderr create mode 100644 src/test/ui/or-patterns/or-patterns-default-binding-modes.rs delete mode 100644 src/test/ui/or-patterns/or-patterns-syntactic-pass.stderr create mode 100644 src/test/ui/or-patterns/search-via-bindings.rs create mode 100644 src/test/ui/or-patterns/slice-patterns.rs create mode 100644 src/test/ui/or-patterns/struct-like.rs delete mode 100644 src/test/ui/overlap-marker-trait.rs delete mode 100644 src/test/ui/overlap-marker-trait.stderr create mode 100644 src/test/ui/parser/assoc-const-underscore-semantic-fail.rs create mode 100644 src/test/ui/parser/assoc-const-underscore-semantic-fail.stderr create mode 100644 src/test/ui/parser/assoc-const-underscore-syntactic-pass.rs create mode 100644 src/test/ui/parser/assoc-static-semantic-fail.rs create mode 100644 src/test/ui/parser/assoc-static-semantic-fail.stderr create mode 100644 src/test/ui/parser/assoc-static-syntactic-fail.rs create mode 100644 src/test/ui/parser/assoc-static-syntactic-fail.stderr create mode 100644 src/test/ui/parser/default-on-wrong-item-kind.rs create mode 100644 src/test/ui/parser/default-on-wrong-item-kind.stderr create mode 100644 src/test/ui/parser/default-unmatched-assoc.rs create mode 100644 src/test/ui/parser/default-unmatched-assoc.stderr create mode 100644 src/test/ui/parser/default-unmatched-extern.rs create mode 100644 src/test/ui/parser/default-unmatched-extern.stderr create mode 100644 src/test/ui/parser/default-unmatched.rs create mode 100644 src/test/ui/parser/default-unmatched.stderr create mode 100644 src/test/ui/parser/doc-comment-in-stmt.rs create mode 100644 src/test/ui/parser/doc-comment-in-stmt.stderr create mode 100644 src/test/ui/parser/extern-crate-async.rs create mode 100644 src/test/ui/parser/fn-body-optional-semantic-fail.rs create mode 100644 src/test/ui/parser/fn-body-optional-semantic-fail.stderr create mode 100644 src/test/ui/parser/fn-body-optional-syntactic-pass.rs create mode 100644 src/test/ui/parser/fn-header-semantic-fail.rs create mode 100644 src/test/ui/parser/fn-header-semantic-fail.stderr create mode 100644 src/test/ui/parser/fn-header-syntactic-pass.rs create mode 100644 src/test/ui/parser/foreign-const-semantic-fail.rs create mode 100644 src/test/ui/parser/foreign-const-semantic-fail.stderr create mode 100644 src/test/ui/parser/foreign-const-syntactic-fail.rs create mode 100644 src/test/ui/parser/foreign-const-syntactic-fail.stderr create mode 100644 src/test/ui/parser/foreign-static-semantic-fail.rs create mode 100644 src/test/ui/parser/foreign-static-semantic-fail.stderr create mode 100644 src/test/ui/parser/foreign-static-syntactic-pass.rs create mode 100644 src/test/ui/parser/foreign-ty-semantic-fail.rs create mode 100644 src/test/ui/parser/foreign-ty-semantic-fail.stderr create mode 100644 src/test/ui/parser/foreign-ty-syntactic-pass.rs create mode 100644 src/test/ui/parser/inner-attr-in-trait-def.rs create mode 100644 src/test/ui/parser/issue-35813-postfix-after-cast.rs create mode 100644 src/test/ui/parser/issue-35813-postfix-after-cast.stderr create mode 100644 src/test/ui/parser/issue-48137-macros-cannot-interpolate-impl-items-bad-variants.rs create mode 100644 src/test/ui/parser/issue-48137-macros-cannot-interpolate-impl-items-bad-variants.stderr create mode 100644 src/test/ui/parser/issue-48137-macros-cannot-interpolate-impl-items.rs create mode 100644 src/test/ui/parser/issue-62894.rs create mode 100644 src/test/ui/parser/issue-62894.stderr create mode 100644 src/test/ui/parser/issue-68629.rs create mode 100644 src/test/ui/parser/issue-68629.stderr create mode 100644 src/test/ui/parser/issue-68730.rs create mode 100644 src/test/ui/parser/issue-68730.stderr create mode 100644 src/test/ui/parser/issue-68788-in-trait-item-propagation.rs create mode 100644 src/test/ui/parser/issue-68890.rs create mode 100644 src/test/ui/parser/issue-68890.stderr create mode 100644 src/test/ui/parser/issue-70050-ntliteral-accepts-negated-lit.rs create mode 100644 src/test/ui/parser/issue-70552-ascription-in-parens-after-call.rs create mode 100644 src/test/ui/parser/issue-70552-ascription-in-parens-after-call.stderr create mode 100644 src/test/ui/parser/item-free-const-no-body-semantic-fail.rs create mode 100644 src/test/ui/parser/item-free-const-no-body-semantic-fail.stderr create mode 100644 src/test/ui/parser/item-free-const-no-body-syntactic-pass.rs create mode 100644 src/test/ui/parser/item-free-static-no-body-semantic-fail.rs create mode 100644 src/test/ui/parser/item-free-static-no-body-semantic-fail.stderr create mode 100644 src/test/ui/parser/item-free-static-no-body-syntactic-pass.rs create mode 100644 src/test/ui/parser/item-free-type-bounds-semantic-fail.rs create mode 100644 src/test/ui/parser/item-free-type-bounds-semantic-fail.stderr create mode 100644 src/test/ui/parser/item-free-type-bounds-syntactic-pass.rs create mode 100644 src/test/ui/parser/missing-semicolon.rs create mode 100644 src/test/ui/parser/missing-semicolon.stderr create mode 100644 src/test/ui/parser/qualified-path-in-turbofish.fixed create mode 100644 src/test/ui/parser/qualified-path-in-turbofish.rs create mode 100644 src/test/ui/parser/qualified-path-in-turbofish.stderr delete mode 100644 src/test/ui/parser/recovery-attr-on-if.rs delete mode 100644 src/test/ui/parser/recovery-attr-on-if.stderr delete mode 100644 src/test/ui/parser/removed-syntax-extern-const.rs delete mode 100644 src/test/ui/parser/removed-syntax-extern-const.stderr create mode 100644 src/test/ui/parser/self-param-semantic-fail.rs create mode 100644 src/test/ui/parser/self-param-semantic-fail.stderr create mode 100644 src/test/ui/parser/self-param-syntactic-pass.rs create mode 100644 src/test/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref-inverse-promotion.rs create mode 100644 src/test/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref-inverse-promotion.stderr create mode 100644 src/test/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref-inverse.rs create mode 100644 src/test/ui/pattern/bindings-after-at/borrowck-pat-by-move-and-ref-inverse.stderr create mode 100644 src/test/ui/pattern/bindings-after-at/box-patterns.rs create mode 100644 src/test/ui/pattern/bindings-after-at/nested-binding-mode-lint.rs create mode 100644 src/test/ui/pattern/bindings-after-at/nested-binding-modes-mut.rs create mode 100644 src/test/ui/pattern/bindings-after-at/nested-binding-modes-mut.stderr create mode 100644 src/test/ui/pattern/bindings-after-at/nested-binding-modes-ref.rs create mode 100644 src/test/ui/pattern/bindings-after-at/nested-binding-modes-ref.stderr create mode 100644 src/test/ui/pattern/bindings-after-at/or-patterns-box-patterns.rs create mode 100644 src/test/ui/pattern/bindings-after-at/or-patterns-slice-patterns.rs create mode 100644 src/test/ui/pattern/bindings-after-at/or-patterns.rs create mode 100644 src/test/ui/pattern/bindings-after-at/slice-patterns.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern-pass.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.stderr create mode 100644 src/test/ui/pattern/move-ref-patterns/by-move-sub-pat-unreachable.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/feature-gate-move_ref_pattern.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/feature-gate-move_ref_pattern.stderr create mode 100644 src/test/ui/pattern/move-ref-patterns/issue-53840.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures-inside.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures-inside.stderr create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures-pass.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-closure-captures.stderr create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-default-binding-modes.rs create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-default-binding-modes.stderr create mode 100644 src/test/ui/pattern/move-ref-patterns/move-ref-patterns-dynamic-semantics.rs create mode 100644 src/test/ui/proc-macro/auxiliary/generate-dollar-ident.rs create mode 100644 src/test/ui/proc-macro/auxiliary/issue-59191.rs create mode 100644 src/test/ui/proc-macro/generate-dollar-ident.rs create mode 100644 src/test/ui/proc-macro/issue-59191-replace-root-with-fn.rs create mode 100644 src/test/ui/proc-macro/issue-59191-replace-root-with-fn.stderr create mode 100644 src/test/ui/proc-macro/trait-fn-args-2015.rs create mode 100644 src/test/ui/recursion_limit/empty.rs create mode 100644 src/test/ui/recursion_limit/empty.stderr create mode 100644 src/test/ui/recursion_limit/invalid_digit.rs create mode 100644 src/test/ui/recursion_limit/invalid_digit.stderr create mode 100644 src/test/ui/recursion_limit/overflow.rs create mode 100644 src/test/ui/recursion_limit/overflow.stderr create mode 100644 src/test/ui/recursion_limit/zero.rs create mode 100644 src/test/ui/recursion_limit/zero.stderr create mode 100644 src/test/ui/repr/feature-gate-no-niche.rs create mode 100644 src/test/ui/repr/feature-gate-no-niche.stderr create mode 100644 src/test/ui/repr/repr-no-niche-inapplicable-to-unions.rs create mode 100644 src/test/ui/repr/repr-no-niche-inapplicable-to-unions.stderr create mode 100644 src/test/ui/repr/repr-no-niche.rs create mode 100644 src/test/ui/resolve/issue-69401-trait-fn-no-body-ty-local.rs create mode 100644 src/test/ui/resolve/issue-69401-trait-fn-no-body-ty-local.stderr create mode 100644 src/test/ui/resolve/typo-suggestion-named-underscore.rs create mode 100644 src/test/ui/resolve/typo-suggestion-named-underscore.stderr create mode 100644 src/test/ui/rfc-2091-track-caller/caller-location-fnptr-rt-ctfe-equiv.rs create mode 100644 src/test/ui/rfc-2091-track-caller/caller-location-fnptr-rt-ctfe-equiv.stderr create mode 100644 src/test/ui/rfc-2632-const-trait-impl/assoc-type.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/call-const-trait-method-fail.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/call-const-trait-method-fail.stderr create mode 100644 src/test/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr create mode 100644 src/test/ui/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/const-check-fns-in-const-impl.stderr create mode 100644 src/test/ui/rfc-2632-const-trait-impl/generic-bound.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/stability.rs create mode 100644 src/test/ui/rfc-2632-const-trait-impl/stability.stderr create mode 100644 src/test/ui/rfc1623-2.rs create mode 100644 src/test/ui/rfc1623-2.stderr create mode 100644 src/test/ui/sanitize-inline-always.rs create mode 100644 src/test/ui/sanitize-inline-always.stderr create mode 100644 src/test/ui/sanitize/address.rs create mode 100644 src/test/ui/sanitize/badfree.rs rename src/test/ui/{sanitize-cfg.rs => sanitize/cfg.rs} (100%) rename src/test/ui/{sanitizer-leak.rs => sanitize/leak.rs} (100%) rename src/test/ui/{sanitizer-memory.rs => sanitize/memory.rs} (100%) create mode 100644 src/test/ui/sanitize/new-llvm-pass-manager-thin-lto.rs rename src/test/ui/{sanitizer-unsupported-target.rs => sanitize/unsupported-target.rs} (100%) rename src/test/ui/{sanitizer-unsupported-target.stderr => sanitize/unsupported-target.stderr} (100%) create mode 100644 src/test/ui/sanitize/use-after-scope.rs delete mode 100644 src/test/ui/sanitizer-address.rs create mode 100644 src/test/ui/save-analysis/issue-68621.rs create mode 100644 src/test/ui/save-analysis/issue-68621.stderr create mode 100644 src/test/ui/shadow-bool.rs create mode 100644 src/test/ui/specialization/issue-39618.rs create mode 100644 src/test/ui/specialization/soundness/partial_eq_range_inclusive.rs create mode 100644 src/test/ui/specialization/soundness/partial_ord_slice.rs create mode 100644 src/test/ui/suggestions/const-in-struct-pat.rs create mode 100644 src/test/ui/suggestions/const-in-struct-pat.stderr create mode 100644 src/test/ui/suggestions/expected-boxed-future-isnt-pinned.rs create mode 100644 src/test/ui/suggestions/expected-boxed-future-isnt-pinned.stderr create mode 100644 src/test/ui/suggestions/fn-missing-lifetime-in-item.rs create mode 100644 src/test/ui/suggestions/fn-missing-lifetime-in-item.stderr create mode 100644 src/test/ui/suggestions/impl-trait-missing-lifetime.rs create mode 100644 src/test/ui/suggestions/impl-trait-missing-lifetime.stderr create mode 100644 src/test/ui/suggestions/method-missing-parentheses.rs create mode 100644 src/test/ui/suggestions/method-missing-parentheses.stderr create mode 100644 src/test/ui/suggestions/missing-assoc-fn-applicable-suggestions.fixed create mode 100644 src/test/ui/suggestions/missing-assoc-fn-applicable-suggestions.rs create mode 100644 src/test/ui/suggestions/missing-assoc-fn-applicable-suggestions.stderr create mode 100644 src/test/ui/suggestions/missing-assoc-fn.rs create mode 100644 src/test/ui/suggestions/missing-assoc-fn.stderr create mode 100644 src/test/ui/suggestions/missing-trait-bounds-for-method-call.rs create mode 100644 src/test/ui/suggestions/missing-trait-bounds-for-method-call.stderr create mode 100644 src/test/ui/suggestions/object-unsafe-trait-references-self.rs create mode 100644 src/test/ui/suggestions/object-unsafe-trait-references-self.stderr create mode 100644 src/test/ui/suggestions/object-unsafe-trait-should-use-self.rs create mode 100644 src/test/ui/suggestions/object-unsafe-trait-should-use-self.stderr create mode 100644 src/test/ui/suggestions/object-unsafe-trait-should-use-where-sized.fixed create mode 100644 src/test/ui/suggestions/object-unsafe-trait-should-use-where-sized.rs create mode 100644 src/test/ui/suggestions/object-unsafe-trait-should-use-where-sized.stderr create mode 100644 src/test/ui/suggestions/struct-initializer-comma.rs create mode 100644 src/test/ui/suggestions/struct-initializer-comma.stderr create mode 100644 src/test/ui/suggestions/suggest-split-at-mut.rs create mode 100644 src/test/ui/suggestions/suggest-split-at-mut.stderr create mode 100644 src/test/ui/test-panic-abort-nocapture.rs create mode 100644 src/test/ui/test-panic-abort-nocapture.run.stderr create mode 100644 src/test/ui/test-panic-abort-nocapture.run.stdout create mode 100644 src/test/ui/traits/overlap-not-permitted-for-builtin-trait.rs create mode 100644 src/test/ui/traits/overlap-not-permitted-for-builtin-trait.stderr delete mode 100644 src/test/ui/traits/overlap-permitted-for-marker-traits-neg.rs delete mode 100644 src/test/ui/traits/overlap-permitted-for-marker-traits.rs create mode 100644 src/test/ui/type-alias-impl-trait/assoc-type-lifetime-unconstrained.rs create mode 100644 src/test/ui/type-alias-impl-trait/assoc-type-lifetime-unconstrained.stderr create mode 100644 src/test/ui/type-alias-impl-trait/issue-67844-nested-opaque.rs create mode 100644 src/test/ui/typeck/typeck_type_placeholder_item.rs create mode 100644 src/test/ui/typeck/typeck_type_placeholder_item.stderr create mode 100644 src/test/ui/use-module-level-int-consts.rs create mode 100755 src/tools/linkchecker/linkcheck.sh delete mode 100644 vendor/chalk-engine/.cargo-checksum.json delete mode 100644 vendor/chalk-engine/Cargo.toml delete mode 100644 vendor/chalk-engine/README.md delete mode 100644 vendor/chalk-engine/src/README.md delete mode 100644 vendor/chalk-engine/src/context.rs delete mode 100644 vendor/chalk-engine/src/context/prelude.rs delete mode 100644 vendor/chalk-engine/src/derived.rs delete mode 100644 vendor/chalk-engine/src/fallible.rs delete mode 100644 vendor/chalk-engine/src/forest.rs delete mode 100644 vendor/chalk-engine/src/hh.rs delete mode 100644 vendor/chalk-engine/src/lib.rs delete mode 100644 vendor/chalk-engine/src/logic.rs delete mode 100644 vendor/chalk-engine/src/simplify.rs delete mode 100644 vendor/chalk-engine/src/stack.rs delete mode 100644 vendor/chalk-engine/src/strand.rs delete mode 100644 vendor/chalk-engine/src/table.rs delete mode 100644 vendor/chalk-engine/src/tables.rs delete mode 100644 vendor/chalk-macros/.cargo-checksum.json delete mode 100644 vendor/chalk-macros/Cargo.toml delete mode 100644 vendor/chalk-macros/README.md delete mode 100644 vendor/chalk-macros/src/index.rs delete mode 100644 vendor/chalk-macros/src/lib.rs create mode 100644 vendor/crossbeam-channel/Cargo.lock create mode 100644 vendor/crossbeam-channel/benches/crossbeam.rs create mode 100644 vendor/crossbeam-channel/tests/same_channel.rs create mode 100644 vendor/crossbeam-utils/.cargo-checksum.json create mode 100644 vendor/crossbeam-utils/CHANGELOG.md create mode 100644 vendor/crossbeam-utils/Cargo.toml rename vendor/{lazy_static-0.2.11 => crossbeam-utils}/LICENSE-APACHE (100%) create mode 100644 vendor/crossbeam-utils/LICENSE-MIT create mode 100644 vendor/crossbeam-utils/README.md create mode 100644 vendor/crossbeam-utils/benches/atomic_cell.rs create mode 100644 vendor/crossbeam-utils/build.rs create mode 100644 vendor/crossbeam-utils/src/atomic/atomic_cell.rs create mode 100644 vendor/crossbeam-utils/src/atomic/consume.rs create mode 100644 vendor/crossbeam-utils/src/atomic/mod.rs create mode 100644 vendor/crossbeam-utils/src/atomic/seq_lock.rs create mode 100644 vendor/crossbeam-utils/src/atomic/seq_lock_wide.rs create mode 100644 vendor/crossbeam-utils/src/backoff.rs create mode 100644 vendor/crossbeam-utils/src/cache_padded.rs create mode 100644 vendor/crossbeam-utils/src/lib.rs create mode 100644 vendor/crossbeam-utils/src/sync/mod.rs create mode 100644 vendor/crossbeam-utils/src/sync/parker.rs create mode 100644 vendor/crossbeam-utils/src/sync/sharded_lock.rs create mode 100644 vendor/crossbeam-utils/src/sync/wait_group.rs create mode 100644 vendor/crossbeam-utils/src/thread.rs create mode 100644 vendor/crossbeam-utils/tests/atomic_cell.rs create mode 100644 vendor/crossbeam-utils/tests/cache_padded.rs create mode 100644 vendor/crossbeam-utils/tests/parker.rs create mode 100644 vendor/crossbeam-utils/tests/sharded_lock.rs create mode 100644 vendor/crossbeam-utils/tests/thread.rs create mode 100644 vendor/crossbeam-utils/tests/wait_group.rs delete mode 100644 vendor/filetime/appveyor.yml create mode 100644 vendor/filetime/src/unix/macos.rs create mode 100644 vendor/filetime/src/wasm.rs delete mode 100644 vendor/kernel32-sys/.cargo-checksum.json delete mode 100644 vendor/kernel32-sys/Cargo.toml delete mode 100644 vendor/kernel32-sys/README.md delete mode 100644 vendor/kernel32-sys/build.rs delete mode 100644 vendor/kernel32-sys/src/lib.rs delete mode 100644 vendor/lazy_static-0.2.11/.cargo-checksum.json delete mode 100644 vendor/lazy_static-0.2.11/Cargo.toml delete mode 100644 vendor/lazy_static-0.2.11/LICENSE-MIT delete mode 100644 vendor/lazy_static-0.2.11/README.md delete mode 100644 vendor/lazy_static-0.2.11/appveyor.yml delete mode 100644 vendor/lazy_static-0.2.11/src/core_lazy.rs delete mode 100644 vendor/lazy_static-0.2.11/src/lazy.rs delete mode 100644 vendor/lazy_static-0.2.11/src/lib.rs delete mode 100644 vendor/lazy_static-0.2.11/src/nightly_lazy.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/compile-fail/README.md delete mode 100644 vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/compile_tests.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/no_std.rs delete mode 100644 vendor/lazy_static-0.2.11/tests/test.rs create mode 100644 vendor/memchr/rustfmt.toml create mode 100644 vendor/memchr/src/tests/miri.rs rename vendor/{parking_lot => parking_lot-0.9.0}/.cargo-checksum.json (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/CHANGELOG.md (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/Cargo.toml (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/LICENSE-APACHE (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/LICENSE-MIT (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/README.md (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/appveyor.yml (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/build.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/condvar.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/deadlock.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/elision.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/lib.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/mutex.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/once.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/raw_mutex.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/raw_rwlock.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/remutex.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/rwlock.rs (100%) rename vendor/{parking_lot => parking_lot-0.9.0}/src/util.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/.cargo-checksum.json (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/Cargo.toml (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/LICENSE-APACHE (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/LICENSE-MIT (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/build.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/lib.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/parking_lot.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/spinwait.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/cloudabi.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/generic.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/linux.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/mod.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/redox.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/sgx.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/unix.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/wasm.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/wasm_atomic.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/windows/keyed_event.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/windows/mod.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/thread_parker/windows/waitaddress.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/util.rs (100%) rename vendor/{parking_lot_core => parking_lot_core-0.6.2}/src/word_lock.rs (100%) delete mode 100644 vendor/pulldown-cmark-0.5.3/.cargo-checksum.json delete mode 100644 vendor/pulldown-cmark-0.5.3/CONTRIBUTING.md delete mode 100644 vendor/pulldown-cmark-0.5.3/Cargo.toml delete mode 100644 vendor/pulldown-cmark-0.5.3/README.md delete mode 100644 vendor/pulldown-cmark-0.5.3/azure-pipelines.yml delete mode 100644 vendor/pulldown-cmark-0.5.3/benches/lib.rs delete mode 100644 vendor/pulldown-cmark-0.5.3/specs/footnotes.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/specs/regression.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/specs/table.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/src/lib.rs delete mode 100644 vendor/pulldown-cmark-0.5.3/src/main.rs delete mode 100644 vendor/pulldown-cmark-0.5.3/tests/suite/regression.rs delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/CommonMark/LICENSE delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/CommonMark/README.google delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/CommonMark/spec.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/GitHub/LICENSE delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/GitHub/gfm_strikethrough.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/GitHub/gfm_table.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/GitHub/gfm_tasklist.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/GitHub/spec.txt delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/xi-editor/LICENSE delete mode 100644 vendor/pulldown-cmark-0.5.3/third_party/xi-editor/crdt.md delete mode 100644 vendor/pulldown-cmark-0.5.3/tools/mk_entities.py delete mode 100644 vendor/pulldown-cmark-0.5.3/tools/mk_puncttable.py create mode 100644 vendor/pulldown-cmark-0.6.1/.cargo-checksum.json create mode 100644 vendor/pulldown-cmark-0.6.1/CONTRIBUTING.md create mode 100644 vendor/pulldown-cmark-0.6.1/Cargo.lock create mode 100644 vendor/pulldown-cmark-0.6.1/Cargo.toml rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/LICENSE (100%) create mode 100644 vendor/pulldown-cmark-0.6.1/README.md rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/benches/html_rendering.rs (100%) create mode 100644 vendor/pulldown-cmark-0.6.1/benches/lib.rs rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/build.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/examples/event-filter.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/examples/string-to-string.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/entities.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/escape.rs (90%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/html.rs (96%) create mode 100644 vendor/pulldown-cmark-0.6.1/src/lib.rs rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/linklabel.rs (85%) create mode 100644 vendor/pulldown-cmark-0.6.1/src/main.rs rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/parse.rs (85%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/puncttable.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/scanners.rs (86%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/simd.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/strings.rs (86%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/src/tree.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/errors.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/html.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/lib.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/footnotes.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/gfm_strikethrough.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/gfm_table.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/gfm_tasklist.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/mod.rs (100%) create mode 100644 vendor/pulldown-cmark-0.6.1/tests/suite/regression.rs rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/spec.rs (100%) rename vendor/{pulldown-cmark-0.5.3 => pulldown-cmark-0.6.1}/tests/suite/table.rs (100%) delete mode 100644 vendor/tar/tests/archives/directory.tar delete mode 100644 vendor/tar/tests/archives/duplicate_dirs.tar delete mode 100644 vendor/tar/tests/archives/empty_filename.tar delete mode 100644 vendor/tar/tests/archives/file_times.tar delete mode 100644 vendor/tar/tests/archives/link.tar delete mode 100644 vendor/tar/tests/archives/pax.tar delete mode 100644 vendor/tar/tests/archives/pax2.tar delete mode 100644 vendor/tar/tests/archives/reading_files.tar delete mode 100644 vendor/tar/tests/archives/simple.tar delete mode 100644 vendor/tar/tests/archives/simple_missing_last_header.tar delete mode 100644 vendor/tar/tests/archives/spaces.tar delete mode 100644 vendor/tar/tests/archives/sparse.tar delete mode 100644 vendor/tar/tests/archives/xattrs.tar delete mode 100644 vendor/term_size/.cargo-checksum.json delete mode 100644 vendor/term_size/CHANGELOG.md delete mode 100644 vendor/term_size/CONTRIBUTORS.md delete mode 100644 vendor/term_size/Cargo.toml delete mode 100644 vendor/term_size/LICENSE-MIT delete mode 100644 vendor/term_size/README.md delete mode 100644 vendor/term_size/appveyor.yml delete mode 100644 vendor/term_size/index.html delete mode 100644 vendor/term_size/justfile delete mode 100644 vendor/term_size/rustfmt.toml delete mode 100644 vendor/term_size/src/lib.rs create mode 100644 vendor/termize/.cargo-checksum.json create mode 100644 vendor/termize/CHANGELOG.md create mode 100644 vendor/termize/CODE_OF_CONDUCT.md create mode 100644 vendor/termize/CONTRIBUTING.md create mode 100644 vendor/termize/Cargo.toml rename vendor/{term_size => termize}/LICENSE-APACHE (100%) create mode 100644 vendor/termize/LICENSE-MIT create mode 100644 vendor/termize/README.md create mode 100644 vendor/termize/src/lib.rs create mode 100644 vendor/termize/src/platform/mod.rs create mode 100644 vendor/termize/src/platform/unix.rs create mode 100644 vendor/termize/src/platform/unsupported.rs create mode 100644 vendor/termize/src/platform/windows.rs create mode 100644 vendor/thread_local-0.3.6/.cargo-checksum.json create mode 100644 vendor/thread_local-0.3.6/Cargo.toml rename vendor/{version_check-0.1.5 => thread_local-0.3.6}/LICENSE-APACHE (100%) create mode 100644 vendor/thread_local-0.3.6/LICENSE-MIT create mode 100644 vendor/thread_local-0.3.6/README.md create mode 100644 vendor/thread_local-0.3.6/benches/thread_local.rs create mode 100644 vendor/thread_local-0.3.6/src/lib.rs create mode 100644 vendor/thread_local-0.3.6/src/thread_id.rs create mode 100644 vendor/thread_local-0.3.6/src/unreachable.rs create mode 100644 vendor/thread_local/src/cached.rs delete mode 100644 vendor/version_check-0.1.5/.cargo-checksum.json delete mode 100644 vendor/version_check-0.1.5/Cargo.toml delete mode 100644 vendor/version_check-0.1.5/README.md delete mode 100644 vendor/version_check-0.1.5/src/lib.rs create mode 100644 vendor/version_check/.cargo-checksum.json create mode 100644 vendor/version_check/Cargo.toml create mode 100644 vendor/version_check/LICENSE-APACHE rename vendor/{version_check-0.1.5 => version_check}/LICENSE-MIT (100%) create mode 100644 vendor/version_check/README.md create mode 100644 vendor/version_check/src/channel.rs create mode 100644 vendor/version_check/src/date.rs create mode 100644 vendor/version_check/src/lib.rs create mode 100644 vendor/version_check/src/version.rs delete mode 100644 vendor/winapi-0.2.8/.cargo-checksum.json delete mode 100644 vendor/winapi-0.2.8/Cargo.toml delete mode 100644 vendor/winapi-0.2.8/LICENSE.md delete mode 100644 vendor/winapi-0.2.8/src/activation.rs delete mode 100644 vendor/winapi-0.2.8/src/audioclient.rs delete mode 100644 vendor/winapi-0.2.8/src/audiosessiontypes.rs delete mode 100644 vendor/winapi-0.2.8/src/basetsd.rs delete mode 100644 vendor/winapi-0.2.8/src/bcrypt.rs delete mode 100644 vendor/winapi-0.2.8/src/cfg.rs delete mode 100644 vendor/winapi-0.2.8/src/cfgmgr32.rs delete mode 100644 vendor/winapi-0.2.8/src/combaseapi.rs delete mode 100644 vendor/winapi-0.2.8/src/commctrl.rs delete mode 100644 vendor/winapi-0.2.8/src/commdlg.rs delete mode 100644 vendor/winapi-0.2.8/src/corsym.rs delete mode 100644 vendor/winapi-0.2.8/src/d2d1.rs delete mode 100644 vendor/winapi-0.2.8/src/d2dbasetypes.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d10shader.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d11.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d11shader.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d12.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d12sdklayers.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d12shader.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d9.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d9caps.rs delete mode 100644 vendor/winapi-0.2.8/src/d3d9types.rs delete mode 100644 vendor/winapi-0.2.8/src/d3dcommon.rs delete mode 100644 vendor/winapi-0.2.8/src/d3dcompiler.rs delete mode 100644 vendor/winapi-0.2.8/src/dbghelp.rs delete mode 100644 vendor/winapi-0.2.8/src/dcommon.rs delete mode 100644 vendor/winapi-0.2.8/src/devpropdef.rs delete mode 100644 vendor/winapi-0.2.8/src/docobj.rs delete mode 100644 vendor/winapi-0.2.8/src/dpapi.rs delete mode 100644 vendor/winapi-0.2.8/src/dsgetdc.rs delete mode 100644 vendor/winapi-0.2.8/src/dsound.rs delete mode 100644 vendor/winapi-0.2.8/src/dsrole.rs delete mode 100644 vendor/winapi-0.2.8/src/dwmapi.rs delete mode 100644 vendor/winapi-0.2.8/src/dwrite.rs delete mode 100644 vendor/winapi-0.2.8/src/dxgi.rs delete mode 100644 vendor/winapi-0.2.8/src/dxgi1_2.rs delete mode 100644 vendor/winapi-0.2.8/src/dxgi1_3.rs delete mode 100644 vendor/winapi-0.2.8/src/dxgi1_4.rs delete mode 100644 vendor/winapi-0.2.8/src/dxgiformat.rs delete mode 100644 vendor/winapi-0.2.8/src/dxgitype.rs delete mode 100644 vendor/winapi-0.2.8/src/errhandlingapi.rs delete mode 100644 vendor/winapi-0.2.8/src/excpt.rs delete mode 100644 vendor/winapi-0.2.8/src/fileapi.rs delete mode 100644 vendor/winapi-0.2.8/src/gl.rs delete mode 100644 vendor/winapi-0.2.8/src/guiddef.rs delete mode 100644 vendor/winapi-0.2.8/src/heapapi.rs delete mode 100644 vendor/winapi-0.2.8/src/hidclass.rs delete mode 100644 vendor/winapi-0.2.8/src/hidpi.rs delete mode 100644 vendor/winapi-0.2.8/src/hidsdi.rs delete mode 100644 vendor/winapi-0.2.8/src/hidusage.rs delete mode 100644 vendor/winapi-0.2.8/src/hstring.rs delete mode 100644 vendor/winapi-0.2.8/src/http.rs delete mode 100644 vendor/winapi-0.2.8/src/imm.rs delete mode 100644 vendor/winapi-0.2.8/src/inaddr.rs delete mode 100644 vendor/winapi-0.2.8/src/inspectable.rs delete mode 100644 vendor/winapi-0.2.8/src/ksmedia.rs delete mode 100644 vendor/winapi-0.2.8/src/lib.rs delete mode 100644 vendor/winapi-0.2.8/src/libloaderapi.rs delete mode 100644 vendor/winapi-0.2.8/src/lmaccess.rs delete mode 100644 vendor/winapi-0.2.8/src/lmcons.rs delete mode 100644 vendor/winapi-0.2.8/src/lmdfs.rs delete mode 100644 vendor/winapi-0.2.8/src/lmerrlog.rs delete mode 100644 vendor/winapi-0.2.8/src/lmjoin.rs delete mode 100644 vendor/winapi-0.2.8/src/lsalookup.rs delete mode 100644 vendor/winapi-0.2.8/src/macros.rs delete mode 100644 vendor/winapi-0.2.8/src/memoryapi.rs delete mode 100644 vendor/winapi-0.2.8/src/minschannel.rs delete mode 100644 vendor/winapi-0.2.8/src/minwinbase.rs delete mode 100644 vendor/winapi-0.2.8/src/minwindef.rs delete mode 100644 vendor/winapi-0.2.8/src/mmdeviceapi.rs delete mode 100644 vendor/winapi-0.2.8/src/mmreg.rs delete mode 100644 vendor/winapi-0.2.8/src/mmsystem.rs delete mode 100644 vendor/winapi-0.2.8/src/mscat.rs delete mode 100644 vendor/winapi-0.2.8/src/mssip.rs delete mode 100644 vendor/winapi-0.2.8/src/nb30.rs delete mode 100644 vendor/winapi-0.2.8/src/ncrypt.rs delete mode 100644 vendor/winapi-0.2.8/src/ntdef.rs delete mode 100644 vendor/winapi-0.2.8/src/ntsecapi.rs delete mode 100644 vendor/winapi-0.2.8/src/ntstatus.rs delete mode 100644 vendor/winapi-0.2.8/src/oaidl.rs delete mode 100644 vendor/winapi-0.2.8/src/objbase.rs delete mode 100644 vendor/winapi-0.2.8/src/objidl.rs delete mode 100644 vendor/winapi-0.2.8/src/objidlbase.rs delete mode 100644 vendor/winapi-0.2.8/src/olectl.rs delete mode 100644 vendor/winapi-0.2.8/src/pdh.rs delete mode 100644 vendor/winapi-0.2.8/src/playsoundapi.rs delete mode 100644 vendor/winapi-0.2.8/src/processsnapshot.rs delete mode 100644 vendor/winapi-0.2.8/src/processthreadsapi.rs delete mode 100644 vendor/winapi-0.2.8/src/propidl.rs delete mode 100644 vendor/winapi-0.2.8/src/propsys.rs delete mode 100644 vendor/winapi-0.2.8/src/prsht.rs delete mode 100644 vendor/winapi-0.2.8/src/psapi.rs delete mode 100644 vendor/winapi-0.2.8/src/qos.rs delete mode 100644 vendor/winapi-0.2.8/src/reason.rs delete mode 100644 vendor/winapi-0.2.8/src/restrictederrorinfo.rs delete mode 100644 vendor/winapi-0.2.8/src/roapi.rs delete mode 100644 vendor/winapi-0.2.8/src/roerrorapi.rs delete mode 100644 vendor/winapi-0.2.8/src/rpc.rs delete mode 100644 vendor/winapi-0.2.8/src/rpcdce.rs delete mode 100644 vendor/winapi-0.2.8/src/sapi.rs delete mode 100644 vendor/winapi-0.2.8/src/schannel.rs delete mode 100644 vendor/winapi-0.2.8/src/servprov.rs delete mode 100644 vendor/winapi-0.2.8/src/setupapi.rs delete mode 100644 vendor/winapi-0.2.8/src/shellapi.rs delete mode 100644 vendor/winapi-0.2.8/src/shellscalingapi.rs delete mode 100644 vendor/winapi-0.2.8/src/shlguid.rs delete mode 100644 vendor/winapi-0.2.8/src/shlobj.rs delete mode 100644 vendor/winapi-0.2.8/src/shobjidl.rs delete mode 100644 vendor/winapi-0.2.8/src/shtypes.rs delete mode 100644 vendor/winapi-0.2.8/src/spapidef.rs delete mode 100644 vendor/winapi-0.2.8/src/sql.rs delete mode 100644 vendor/winapi-0.2.8/src/sqltypes.rs delete mode 100644 vendor/winapi-0.2.8/src/sspi.rs delete mode 100644 vendor/winapi-0.2.8/src/strmif.rs delete mode 100644 vendor/winapi-0.2.8/src/subauth.rs delete mode 100644 vendor/winapi-0.2.8/src/synchapi.rs delete mode 100644 vendor/winapi-0.2.8/src/sysinfoapi.rs delete mode 100644 vendor/winapi-0.2.8/src/threadpoolapi.rs delete mode 100644 vendor/winapi-0.2.8/src/timezoneapi.rs delete mode 100644 vendor/winapi-0.2.8/src/tlhelp32.rs delete mode 100644 vendor/winapi-0.2.8/src/unknwnbase.rs delete mode 100644 vendor/winapi-0.2.8/src/urlhist.rs delete mode 100644 vendor/winapi-0.2.8/src/urlmon.rs delete mode 100644 vendor/winapi-0.2.8/src/usb.rs delete mode 100644 vendor/winapi-0.2.8/src/usbspec.rs delete mode 100644 vendor/winapi-0.2.8/src/usp10.rs delete mode 100644 vendor/winapi-0.2.8/src/vadefs.rs delete mode 100644 vendor/winapi-0.2.8/src/vsbackup.rs delete mode 100644 vendor/winapi-0.2.8/src/vss.rs delete mode 100644 vendor/winapi-0.2.8/src/vsserror.rs delete mode 100644 vendor/winapi-0.2.8/src/vswriter.rs delete mode 100644 vendor/winapi-0.2.8/src/werapi.rs delete mode 100644 vendor/winapi-0.2.8/src/winbase.rs delete mode 100644 vendor/winapi-0.2.8/src/wincon.rs delete mode 100644 vendor/winapi-0.2.8/src/wincred.rs delete mode 100644 vendor/winapi-0.2.8/src/wincrypt.rs delete mode 100644 vendor/winapi-0.2.8/src/windef.rs delete mode 100644 vendor/winapi-0.2.8/src/windowscodecs.rs delete mode 100644 vendor/winapi-0.2.8/src/windowsx.rs delete mode 100644 vendor/winapi-0.2.8/src/winerror.rs delete mode 100644 vendor/winapi-0.2.8/src/winevt.rs delete mode 100644 vendor/winapi-0.2.8/src/wingdi.rs delete mode 100644 vendor/winapi-0.2.8/src/winhttp.rs delete mode 100644 vendor/winapi-0.2.8/src/winioctl.rs delete mode 100644 vendor/winapi-0.2.8/src/winnetwk.rs delete mode 100644 vendor/winapi-0.2.8/src/winnls.rs delete mode 100644 vendor/winapi-0.2.8/src/winnt.rs delete mode 100644 vendor/winapi-0.2.8/src/winreg.rs delete mode 100644 vendor/winapi-0.2.8/src/winscard.rs delete mode 100644 vendor/winapi-0.2.8/src/winsmcrd.rs delete mode 100644 vendor/winapi-0.2.8/src/winsock2.rs delete mode 100644 vendor/winapi-0.2.8/src/winspool.rs delete mode 100644 vendor/winapi-0.2.8/src/winstring.rs delete mode 100644 vendor/winapi-0.2.8/src/winsvc.rs delete mode 100644 vendor/winapi-0.2.8/src/winusb.rs delete mode 100644 vendor/winapi-0.2.8/src/winusbio.rs delete mode 100644 vendor/winapi-0.2.8/src/winuser.rs delete mode 100644 vendor/winapi-0.2.8/src/ws2def.rs delete mode 100644 vendor/winapi-0.2.8/src/ws2ipdef.rs delete mode 100644 vendor/winapi-0.2.8/src/ws2spi.rs delete mode 100644 vendor/winapi-0.2.8/src/ws2tcpip.rs delete mode 100644 vendor/winapi-0.2.8/src/wtypes.rs delete mode 100644 vendor/winapi-0.2.8/src/wtypesbase.rs delete mode 100644 vendor/winapi-0.2.8/src/xinput.rs delete mode 100644 vendor/winapi-build/.cargo-checksum.json delete mode 100644 vendor/winapi-build/Cargo.toml delete mode 100644 vendor/winapi-build/src/lib.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc8ca5d07b..d6840b20c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,6 +50,9 @@ is a bug or not, feel free to file a bug anyway. **If you believe reporting your bug publicly represents a security risk to Rust users, please follow our [instructions for reporting security vulnerabilities](https://www.rust-lang.org/policies/security)**. +If you're using the nightly channel, please check if the bug exists in the +latest toolchain before filing your bug. It might be fixed already. + If you have the chance, before reporting a bug, please [search existing issues](https://github.com/rust-lang/rust/search?q=&type=Issues&utf8=%E2%9C%93), as it's possible that someone else has already reported your error. This doesn't diff --git a/Cargo.lock b/Cargo.lock index 80c90243e5..d41517cd4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,9 +121,9 @@ checksum = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" [[package]] name = "backtrace" -version = "0.3.40" +version = "0.3.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924c76597f0d9ca25d762c25a4d369d51267536465dc5064bdf0eb073ed477ea" +checksum = "e4036b9bf40f3cf16aba72a3d65e8a520fc4bafcdc7079aea8f848c58c5b5536" dependencies = [ "backtrace-sys", "cfg-if", @@ -281,7 +281,7 @@ dependencies = [ [[package]] name = "cargo" -version = "0.43.0" +version = "0.44.0" dependencies = [ "anyhow", "atty", @@ -292,6 +292,7 @@ dependencies = [ "clap", "core-foundation 0.7.0", "crates-io", + "crossbeam-channel", "crossbeam-utils 0.7.0", "crypto-hash", "curl", @@ -418,25 +419,6 @@ dependencies = [ "rustc-std-workspace-core", ] -[[package]] -name = "chalk-engine" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ec698a6f053a23bfbe646d9f2fde4b02abc19125595270a99e6f44ae0bdd1a" -dependencies = [ - "chalk-macros", - "rustc-hash", -] - -[[package]] -name = "chalk-macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "295635afd6853aa9f20baeb7f0204862440c0fe994c5a253d5f479dac41d047e" -dependencies = [ - "lazy_static 0.2.11", -] - [[package]] name = "chrono" version = "0.4.6" @@ -473,7 +455,6 @@ dependencies = [ "clippy_lints", "compiletest_rs", "derive-new", - "git2", "lazy_static 1.4.0", "regex", "rustc-workspace-hack", @@ -497,7 +478,7 @@ dependencies = [ "itertools 0.8.0", "lazy_static 1.4.0", "matches", - "pulldown-cmark 0.6.1", + "pulldown-cmark 0.7.0", "quine-mc_cluskey", "regex-syntax", "semver", @@ -721,12 +702,11 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.3.8" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f0ed1a4de2235cabda8558ff5840bffb97fcb64c97827f354a451307df5f72b" +checksum = "acec9a3b0b3559f15aee4f90746c4e5e293b701c0f7d3925d24e01645267b68c" dependencies = [ - "crossbeam-utils 0.6.5", - "smallvec 0.6.10", + "crossbeam-utils 0.7.0", ] [[package]] @@ -879,14 +859,13 @@ dependencies = [ [[package]] name = "derive_more" -version = "0.13.0" +version = "0.99.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f57d78cf3bd45270dad4e70c21ec77a960b36c7a841ff9db76aaa775a8fb871" +checksum = "2159be042979966de68315bce7034bb000c775f22e3e834e1c52ff78f041cae8" dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.12", - "rustc_version", - "syn 0.15.35", + "proc-macro2 1.0.3", + "quote 1.0.2", + "syn 1.0.11", ] [[package]] @@ -1077,13 +1056,14 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" [[package]] name = "filetime" -version = "0.2.4" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2df5c1a8c4be27e7707789dc42ae65976e60b394afd293d1419ab915833e646" +checksum = "1ff6d4dab0aa0c8e6346d46052e93b13a16cf847b54ed357087c35011048cc7d" dependencies = [ "cfg-if", "libc", "redox_syscall", + "winapi 0.3.8", ] [[package]] @@ -1254,9 +1234,9 @@ dependencies = [ [[package]] name = "git2" -version = "0.11.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77519ef7c5beee314d0804d4534f01e0f9e8d9acdee2b7a48627e590b27e0ec4" +checksum = "b7da16ceafe24cedd9ba02c4463a2b506b6493baf4317c79c5acb553134a3c15" dependencies = [ "bitflags", "libc", @@ -1269,9 +1249,9 @@ dependencies = [ [[package]] name = "git2-curl" -version = "0.12.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2559abb1d87d27668d31bd868a000f0e2e0065d10e78961b62da95d7a7f1cc7" +checksum = "502d532a2d06184beb3bc869d4d90236e60934e3382c921b203fa3c33e212bd7" dependencies = [ "curl", "git2", @@ -1537,9 +1517,9 @@ checksum = "c3360c7b59e5ffa2653671fb74b4741a5d343c03f331c0a4aeda42b5c2b0ec7d" [[package]] name = "ignore" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec16832258409d571aaef8273f3c3cc5b060d784e159d1a0f3b0017308f84a7" +checksum = "522daefc3b69036f80c7d2990b28ff9e0471c683bad05ca258e0a01dd22c5a1e" dependencies = [ "crossbeam-channel", "globset", @@ -1548,7 +1528,7 @@ dependencies = [ "memchr", "regex", "same-file", - "thread_local", + "thread_local 1.0.1", "walkdir", "winapi-util", ] @@ -1564,7 +1544,7 @@ dependencies = [ "rand_xoshiro", "sized-chunks", "typenum", - "version_check 0.9.1", + "version_check", ] [[package]] @@ -1657,9 +1637,9 @@ checksum = "9ad0485404155f45cce53a40d4b2d6ac356418300daed05273d9e26f91c390be" [[package]] name = "jsonrpc-client-transports" -version = "13.1.0" +version = "14.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39577db48b004cffb4c5b8e5c9b993c177c52599ecbee88711e815acf65144db" +checksum = "0a9ae166c4d1f702d297cd76d4b55758ace80272ffc6dbb139fdc1bf810de40b" dependencies = [ "failure", "futures", @@ -1676,9 +1656,9 @@ dependencies = [ [[package]] name = "jsonrpc-core" -version = "13.2.0" +version = "14.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91d767c183a7e58618a609499d359ce3820700b3ebb4823a18c343b4a2a41a0d" +checksum = "fe3b688648f1ef5d5072229e2d672ecb92cbff7d1c79bcf3fd5898f3f3df0970" dependencies = [ "futures", "log", @@ -1689,63 +1669,62 @@ dependencies = [ [[package]] name = "jsonrpc-core-client" -version = "13.1.0" +version = "14.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f047c10738edee7c3c6acf5241a0ce33df32ef9230c1a7fb03e4a77ee72c992f" +checksum = "080dc110be17701097df238fad3c816d4a478a1899dfbcf8ec8957dd40ec7304" dependencies = [ "jsonrpc-client-transports", ] [[package]] name = "jsonrpc-derive" -version = "13.1.0" +version = "14.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29f9149f785deaae92a4c834a9a1a83a4313b8cfedccf15362cd4cf039a64501" +checksum = "8609af8f63b626e8e211f52441fcdb6ec54f1a446606b10d5c89ae9bf8a20058" dependencies = [ "proc-macro-crate", - "proc-macro2 0.4.30", - "quote 0.6.12", - "syn 0.15.35", + "proc-macro2 1.0.3", + "quote 1.0.2", + "syn 1.0.11", ] [[package]] name = "jsonrpc-ipc-server" -version = "13.1.0" +version = "14.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "256c5e4292c17b4c2ecdf542299dc8e9d6b3939c075c54825570ad9317fe5751" +checksum = "b579cd0840d7db3ebaadf52f6f31ec601a260e78d610e44f68634f919e34497a" dependencies = [ "jsonrpc-core", "jsonrpc-server-utils", "log", "parity-tokio-ipc", - "parking_lot", + "parking_lot 0.9.0", "tokio-service", ] [[package]] name = "jsonrpc-pubsub" -version = "13.1.0" +version = "14.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2c08b444cc0ed70263798834343d0ac875e664257df8079160f23ac1ea79446" +checksum = "5b31c9b90731276fdd24d896f31bb10aecf2e5151733364ae81123186643d939" dependencies = [ "jsonrpc-core", "log", - "parking_lot", + "parking_lot 0.10.0", "serde", ] [[package]] name = "jsonrpc-server-utils" -version = "13.1.0" +version = "14.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44561bfdd31401bad790527f1e951dde144f2341ddc3e1b859d32945e1a34eff" +checksum = "95b7635e618a0edbbe0d2a2bbbc69874277c49383fcf6c3c0414491cfb517d22" dependencies = [ "bytes", "globset", "jsonrpc-core", "lazy_static 1.4.0", "log", - "num_cpus", "tokio", "tokio-codec", "unicase", @@ -1790,9 +1769,9 @@ dependencies = [ [[package]] name = "libgit2-sys" -version = "0.10.0" +version = "0.12.0+0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9ec6bca50549d34a392611dde775123086acbd994e3fff64954777ce2dc2e51" +checksum = "05dff41ac39e7b653f5f1550886cf00ba52f8e7f57210b633cdeedb3de5b236c" dependencies = [ "cc", "libc", @@ -2009,15 +1988,15 @@ checksum = "fef709d3257013bba7cff14fc504e07e80631d3fe0f6d38ce63b8f6510ccb932" dependencies = [ "byteorder", "memmap", - "parking_lot", + "parking_lot 0.9.0", "rustc-hash", ] [[package]] name = "memchr" -version = "2.2.0" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2efc7bc57c883d4a4d6e3246905283d8dae951bb3bd32f49d6ef297f546e1c39" +checksum = "53445de381a1f436797497c61d851644d0e8e88e6140f22872ad33a704933978" [[package]] name = "memmap" @@ -2157,6 +2136,7 @@ dependencies = [ "rustc-workspace-hack", "rustc_version", "serde", + "serde_json", "shell-escape", "vergen", ] @@ -2351,10 +2331,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" dependencies = [ "lock_api", - "parking_lot_core", + "parking_lot_core 0.6.2", "rustc_version", ] +[[package]] +name = "parking_lot" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc" +dependencies = [ + "lock_api", + "parking_lot_core 0.7.0", +] + [[package]] name = "parking_lot_core" version = "0.6.2" @@ -2370,6 +2360,20 @@ dependencies = [ "winapi 0.3.8", ] +[[package]] +name = "parking_lot_core" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7582838484df45743c8434fbff785e8edf260c28748353d44bc0da32e0ceabf1" +dependencies = [ + "cfg-if", + "cloudabi", + "libc", + "redox_syscall", + "smallvec 1.0.0", + "winapi 0.3.8", +] + [[package]] name = "percent-encoding" version = "1.0.1" @@ -2471,9 +2475,9 @@ checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" [[package]] name = "polonius-engine" -version = "0.11.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e478d7c38eb785c6416cbe58df12aa55d7aefa3759b6d3e044b2ed03f423cec" +checksum = "04d8ef65e3f89ecaec9ca7cb0e0911b4617352d4494018bcf934992f03f2024c" dependencies = [ "datafrog", "log", @@ -2504,12 +2508,11 @@ dependencies = [ [[package]] name = "pretty_env_logger" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df8b3f4e0475def7d9c2e5de8e5a1306949849761e107b360d03e98eafaffd61" +checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d" dependencies = [ - "chrono", - "env_logger 0.6.2", + "env_logger 0.7.1", "log", ] @@ -2582,23 +2585,23 @@ dependencies = [ [[package]] name = "pulldown-cmark" -version = "0.5.3" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77043da1282374688ee212dc44b3f37ff929431de9c9adc3053bd3cee5630357" +checksum = "1c205cc82214f3594e2d50686730314f817c67ffa80fe800cf0db78c3c2b9d9e" dependencies = [ "bitflags", + "getopts", "memchr", "unicase", ] [[package]] name = "pulldown-cmark" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c205cc82214f3594e2d50686730314f817c67ffa80fe800cf0db78c3c2b9d9e" +checksum = "2c2d7fd131800e0d63df52aff46201acaab70b431a4a1ec6f0343fe8e64f35a4" dependencies = [ "bitflags", - "getopts", "memchr", "unicase", ] @@ -2641,18 +2644,24 @@ dependencies = [ [[package]] name = "racer" -version = "2.1.29" +version = "2.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6d7ffceb4da3e0a29c18986f0469c209f4db3ab9f2ffe286eaa1104a3e5028" +checksum = "0ff33fa15ac0384376741d16ddb05a65263dde4e2c5d0f7a9f3747db788764aa" dependencies = [ "bitflags", "clap", "derive_more", - "env_logger 0.6.2", - "humantime 1.3.0", + "env_logger 0.7.1", + "humantime 2.0.0", "lazy_static 1.4.0", "log", "rls-span", + "rustc-ap-rustc_ast_pretty", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_errors", + "rustc-ap-rustc_parse", + "rustc-ap-rustc_session", + "rustc-ap-rustc_span", "rustc-ap-syntax", ] @@ -2876,7 +2885,7 @@ dependencies = [ "aho-corasick", "memchr", "regex-syntax", - "thread_local", + "thread_local 0.3.6", "utf8-ranges", ] @@ -3033,7 +3042,6 @@ version = "0.6.0" dependencies = [ "clippy_lints", "env_logger 0.7.1", - "failure", "futures", "log", "rand 0.7.3", @@ -3067,6 +3075,7 @@ name = "rustbook" version = "0.1.0" dependencies = [ "clap", + "codespan", "codespan-reporting", "failure", "mdbook", @@ -3082,17 +3091,16 @@ dependencies = [ "backtrace", "bitflags", "byteorder", - "chalk-engine", - "fmt_macros", - "graphviz", "jobserver", "log", "measureme", - "parking_lot", + "parking_lot 0.9.0", "polonius-engine", "rustc-rayon", "rustc-rayon-core", "rustc_apfloat", + "rustc_ast", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_feature", @@ -3105,31 +3113,61 @@ dependencies = [ "scoped-tls", "serialize", "smallvec 1.0.0", - "syntax", ] [[package]] name = "rustc-ap-arena" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7475f4c707269b56eb7144c53591e3cd6369a5aa1d66434829ea11df96d5e7e3" +checksum = "ea82fa3d9a8add7422228ca1a2cbba0784fa8861f56148ff64da08b3c7921b03" dependencies = [ "rustc-ap-rustc_data_structures", - "smallvec 0.6.10", + "smallvec 1.0.0", ] [[package]] name = "rustc-ap-graphviz" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e59a55520f140a70a3e0fad80a36e807caa85e9d7016167b91a5b521ea929be" +checksum = "638d0b2b3bcf99824e0cb5a25dbc547b61dc20942e11daf6a97e981918aa18e5" + +[[package]] +name = "rustc-ap-rustc_ast_pretty" +version = "642.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38bab04dd676dee6d2f9670506a18c31bfce38bf7f8420aa83eb1140ecde049" +dependencies = [ + "log", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_span", + "rustc-ap-syntax", +] + +[[package]] +name = "rustc-ap-rustc_attr" +version = "642.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10b843ba8b1ed43739133047673b9f6a54d3b3b4d328d69c6ea89ff971395f35" +dependencies = [ + "rustc-ap-rustc_ast_pretty", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_errors", + "rustc-ap-rustc_feature", + "rustc-ap-rustc_macros", + "rustc-ap-rustc_session", + "rustc-ap-rustc_span", + "rustc-ap-serialize", + "rustc-ap-syntax", + "smallvec 1.0.0", +] [[package]] name = "rustc-ap-rustc_data_structures" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6420857d5a088f680ec1ba736ffba4ee9c1964b0d397e6318f38d461f4f7d5cb" +checksum = "dc3d1c6d0a80ab0c1df76405377cec0f3d5423fb5b0953a8eac70a2ad6c44df2" dependencies = [ + "bitflags", "cfg-if", "crossbeam-utils 0.6.5", "ena", @@ -3137,58 +3175,78 @@ dependencies = [ "jobserver", "lazy_static 1.4.0", "log", - "parking_lot", + "measureme", + "parking_lot 0.9.0", "rustc-ap-graphviz", "rustc-ap-rustc_index", "rustc-ap-serialize", "rustc-hash", "rustc-rayon", "rustc-rayon-core", - "smallvec 0.6.10", + "smallvec 1.0.0", "stable_deref_trait", + "winapi 0.3.8", ] [[package]] name = "rustc-ap-rustc_errors" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8abfca0960131262254a91d02ff4903526a261ede730d7a2c75b4234c867cdc0" +checksum = "4909a1eca29331332257230f29120a8ff68c9e37d868c564fcd599e430cf8914" dependencies = [ "annotate-snippets", "atty", "log", "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_span", "rustc-ap-serialize", - "rustc-ap-syntax_pos", - "term_size", "termcolor", + "termize", "unicode-width", + "winapi 0.3.8", +] + +[[package]] +name = "rustc-ap-rustc_feature" +version = "642.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63ab887a181d795cf5fd3edadf367760deafb90aefb844f168ab5255266e3478" +dependencies = [ + "lazy_static 1.4.0", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_span", ] +[[package]] +name = "rustc-ap-rustc_fs_util" +version = "642.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70814116df3c5fbec8f06f6a1d013ca481f620fd22a9475754e9bf3ee9ba70d8" + [[package]] name = "rustc-ap-rustc_index" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a395509dcb90a92c1479c085639594624e06b4ab3fc7c1b795b46a61f2d4f65" +checksum = "ac1bf1d3cf3d119d41353d6fd229ef7272d5097bc0924de021c0294bf86d48bf" dependencies = [ "rustc-ap-serialize", - "smallvec 0.6.10", + "smallvec 1.0.0", ] [[package]] name = "rustc-ap-rustc_lexer" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64eac8a0e6efb8f55292aa24be0208c7c0538236c613e79952fd1fa3d54bcf8e" +checksum = "4cda21a32cebdc11ec4f5393aa2fcde5ed1b2f673a8571e5a4dcdf07e4ae9cac" dependencies = [ "unicode-xid 0.2.0", ] [[package]] name = "rustc-ap-rustc_macros" -version = "610.0.0" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f99795e8be4877e9e05d59f201e1740c1cf673364655def5848606d9e25b75af" +checksum = "75c47b48ea51910ecfd853c9248a9bf4c767bc823449ab6a1d864dff65fbae16" dependencies = [ "itertools 0.8.0", "proc-macro2 1.0.3", @@ -3198,63 +3256,102 @@ dependencies = [ ] [[package]] -name = "rustc-ap-rustc_target" -version = "610.0.0" +name = "rustc-ap-rustc_parse" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f22e21fdd8e1c0030f507158fa79b9f1e080e6241aba994d0f97c14a0a07a826" +checksum = "abd88e89cd5b5d28dcd3a347a3d534c08627d9455570dc1a2d402cb8437b9d30" dependencies = [ "bitflags", "log", + "rustc-ap-rustc_ast_pretty", + "rustc-ap-rustc_attr", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_errors", + "rustc-ap-rustc_feature", + "rustc-ap-rustc_lexer", + "rustc-ap-rustc_session", + "rustc-ap-rustc_span", + "rustc-ap-syntax", + "smallvec 1.0.0", + "unicode-normalization", +] + +[[package]] +name = "rustc-ap-rustc_session" +version = "642.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8487b4575fbb2d1fc6f1cd61225efd108a4d36817e6fb9b643d57fcae9cb12" +dependencies = [ + "log", + "num_cpus", "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_errors", + "rustc-ap-rustc_feature", + "rustc-ap-rustc_fs_util", "rustc-ap-rustc_index", + "rustc-ap-rustc_span", + "rustc-ap-rustc_target", "rustc-ap-serialize", - "rustc-ap-syntax_pos", + "rustc-ap-syntax", ] [[package]] -name = "rustc-ap-serialize" -version = "610.0.0" +name = "rustc-ap-rustc_span" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb1cd6ef5135408d62559866e79986ca261f4c1333253d500e5e66fe66d1432e" +checksum = "f69746c0d4c21bf20a5bb2bd247261a1aa8631f04202d7303352942dde70d987" dependencies = [ - "indexmap", - "smallvec 0.6.10", + "cfg-if", + "log", + "rustc-ap-arena", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_index", + "rustc-ap-rustc_macros", + "rustc-ap-serialize", + "scoped-tls", + "unicode-width", ] [[package]] -name = "rustc-ap-syntax" -version = "610.0.0" +name = "rustc-ap-rustc_target" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61fc1c901d2cbd24cae95d7bc5a58aa7661ec3dc5320c78c32830a52a685c33c" +checksum = "8bbc6ae09b5d42ec66edd520e8412e0615c53a7c93607fe33dc4abab60ba7c8b" dependencies = [ "bitflags", - "lazy_static 1.4.0", "log", "rustc-ap-rustc_data_structures", - "rustc-ap-rustc_errors", "rustc-ap-rustc_index", - "rustc-ap-rustc_lexer", - "rustc-ap-rustc_target", + "rustc-ap-rustc_macros", + "rustc-ap-rustc_span", "rustc-ap-serialize", - "rustc-ap-syntax_pos", - "scoped-tls", - "smallvec 0.6.10", ] [[package]] -name = "rustc-ap-syntax_pos" -version = "610.0.0" +name = "rustc-ap-serialize" +version = "642.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "230534f638255853bb9f13987537e00a818435a0cc54b68d97221b6822c8f1bc" +checksum = "e13a1ead0252fc3d96da4c336a95950be6795f2b00c84a67ccadf26142f8cb41" dependencies = [ - "cfg-if", - "rustc-ap-arena", + "indexmap", + "smallvec 1.0.0", +] + +[[package]] +name = "rustc-ap-syntax" +version = "642.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1f59f48ca3a2ec16a7e82e718ed5aadf9c9e08cf63015d28b4e774767524a6a" +dependencies = [ + "log", "rustc-ap-rustc_data_structures", "rustc-ap-rustc_index", + "rustc-ap-rustc_lexer", "rustc-ap-rustc_macros", + "rustc-ap-rustc_span", "rustc-ap-serialize", "scoped-tls", - "unicode-width", + "smallvec 1.0.0", ] [[package]] @@ -3352,12 +3449,29 @@ dependencies = [ "smallvec 1.0.0", ] +[[package]] +name = "rustc_ast" +version = "0.0.0" +dependencies = [ + "log", + "rustc_data_structures", + "rustc_index", + "rustc_lexer", + "rustc_macros", + "rustc_span", + "scoped-tls", + "serialize", + "smallvec 1.0.0", +] + [[package]] name = "rustc_ast_lowering" version = "0.0.0" dependencies = [ "log", "rustc", + "rustc_ast", + "rustc_ast_pretty", "rustc_data_structures", "rustc_errors", "rustc_hir", @@ -3366,7 +3480,6 @@ dependencies = [ "rustc_span", "rustc_target", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3374,13 +3487,41 @@ name = "rustc_ast_passes" version = "0.0.0" dependencies = [ "log", + "rustc_ast", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_feature", "rustc_parse", "rustc_session", "rustc_span", - "syntax", +] + +[[package]] +name = "rustc_ast_pretty" +version = "0.0.0" +dependencies = [ + "log", + "rustc_ast", + "rustc_data_structures", + "rustc_span", +] + +[[package]] +name = "rustc_attr" +version = "0.0.0" +dependencies = [ + "rustc_ast", + "rustc_ast_pretty", + "rustc_data_structures", + "rustc_errors", + "rustc_feature", + "rustc_macros", + "rustc_session", + "rustc_span", + "serialize", + "smallvec 1.0.0", ] [[package]] @@ -3389,6 +3530,9 @@ version = "0.0.0" dependencies = [ "fmt_macros", "log", + "rustc_ast", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_expand", @@ -3398,7 +3542,6 @@ dependencies = [ "rustc_span", "rustc_target", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3409,8 +3552,11 @@ dependencies = [ "flate2", "libc", "log", + "measureme", "rustc", "rustc-demangle", + "rustc_ast", + "rustc_attr", "rustc_codegen_ssa", "rustc_codegen_utils", "rustc_data_structures", @@ -3426,7 +3572,6 @@ dependencies = [ "rustc_target", "serialize", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3442,6 +3587,8 @@ dependencies = [ "num_cpus", "rustc", "rustc_apfloat", + "rustc_ast", + "rustc_attr", "rustc_codegen_utils", "rustc_data_structures", "rustc_errors", @@ -3453,7 +3600,6 @@ dependencies = [ "rustc_span", "rustc_target", "serialize", - "syntax", "tempfile", ] @@ -3465,12 +3611,12 @@ dependencies = [ "punycode", "rustc", "rustc-demangle", + "rustc_ast", "rustc_data_structures", "rustc_hir", "rustc_metadata", "rustc_span", "rustc_target", - "syntax", ] [[package]] @@ -3487,7 +3633,7 @@ dependencies = [ "lazy_static 1.4.0", "log", "measureme", - "parking_lot", + "parking_lot 0.9.0", "rustc-hash", "rustc-rayon", "rustc-rayon-core", @@ -3506,6 +3652,9 @@ dependencies = [ "lazy_static 1.4.0", "log", "rustc", + "rustc_ast", + "rustc_ast_pretty", + "rustc_codegen_ssa", "rustc_codegen_utils", "rustc_data_structures", "rustc_error_codes", @@ -3522,7 +3671,6 @@ dependencies = [ "rustc_span", "rustc_target", "serialize", - "syntax", "winapi 0.3.8", ] @@ -3540,8 +3688,8 @@ dependencies = [ "rustc_data_structures", "rustc_span", "serialize", - "term_size", "termcolor", + "termize", "unicode-width", "winapi 0.3.8", ] @@ -3551,7 +3699,10 @@ name = "rustc_expand" version = "0.0.0" dependencies = [ "log", + "rustc_ast", "rustc_ast_passes", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_feature", @@ -3561,7 +3712,6 @@ dependencies = [ "rustc_span", "serialize", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3581,16 +3731,17 @@ version = "0.0.0" name = "rustc_hir" version = "0.0.0" dependencies = [ + "lazy_static 1.4.0", + "rustc_ast", + "rustc_ast_pretty", "rustc_data_structures", "rustc_errors", "rustc_index", "rustc_macros", - "rustc_session", "rustc_span", "rustc_target", "serialize", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3601,13 +3752,13 @@ dependencies = [ "log", "rand 0.7.3", "rustc", + "rustc_ast", "rustc_data_structures", "rustc_fs_util", "rustc_hir", "rustc_session", "rustc_span", "serialize", - "syntax", ] [[package]] @@ -3618,6 +3769,28 @@ dependencies = [ "smallvec 1.0.0", ] +[[package]] +name = "rustc_infer" +version = "0.0.0" +dependencies = [ + "fmt_macros", + "graphviz", + "log", + "rustc", + "rustc_ast", + "rustc_attr", + "rustc_data_structures", + "rustc_error_codes", + "rustc_errors", + "rustc_hir", + "rustc_index", + "rustc_macros", + "rustc_session", + "rustc_span", + "rustc_target", + "smallvec 1.0.0", +] + [[package]] name = "rustc_interface" version = "0.0.0" @@ -3626,8 +3799,10 @@ dependencies = [ "once_cell", "rustc", "rustc-rayon", + "rustc_ast", "rustc_ast_lowering", "rustc_ast_passes", + "rustc_attr", "rustc_builtin_macros", "rustc_codegen_llvm", "rustc_codegen_ssa", @@ -3637,6 +3812,7 @@ dependencies = [ "rustc_expand", "rustc_hir", "rustc_incremental", + "rustc_infer", "rustc_lint", "rustc_metadata", "rustc_mir", @@ -3654,7 +3830,6 @@ dependencies = [ "rustc_typeck", "serialize", "smallvec 1.0.0", - "syntax", "tempfile", "winapi 0.3.8", ] @@ -3672,15 +3847,18 @@ version = "0.0.0" dependencies = [ "log", "rustc", + "rustc_ast", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_feature", "rustc_hir", "rustc_index", + "rustc_infer", "rustc_session", "rustc_span", "rustc_target", - "syntax", "unicode-security", ] @@ -3697,7 +3875,6 @@ dependencies = [ name = "rustc_macros" version = "0.1.0" dependencies = [ - "itertools 0.8.0", "proc-macro2 1.0.3", "quote 1.0.2", "syn 1.0.11", @@ -3712,6 +3889,9 @@ dependencies = [ "log", "memmap", "rustc", + "rustc_ast", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_expand", @@ -3723,7 +3903,6 @@ dependencies = [ "serialize", "smallvec 1.0.0", "stable_deref_trait", - "syntax", "winapi 0.3.8", ] @@ -3739,17 +3918,20 @@ dependencies = [ "polonius-engine", "rustc", "rustc_apfloat", + "rustc_ast", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_hir", "rustc_index", + "rustc_infer", "rustc_lexer", "rustc_macros", "rustc_span", "rustc_target", "serialize", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3757,21 +3939,22 @@ name = "rustc_mir_build" version = "0.0.0" dependencies = [ "arena", - "itertools 0.8.0", "log", "rustc", "rustc_apfloat", + "rustc_ast", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_hir", "rustc_index", + "rustc_infer", "rustc_macros", "rustc_session", "rustc_span", "rustc_target", "serialize", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3780,6 +3963,9 @@ version = "0.0.0" dependencies = [ "bitflags", "log", + "rustc_ast", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_feature", @@ -3787,7 +3973,6 @@ dependencies = [ "rustc_session", "rustc_span", "smallvec 1.0.0", - "syntax", "unicode-normalization", ] @@ -3797,15 +3982,17 @@ version = "0.0.0" dependencies = [ "log", "rustc", + "rustc_ast", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_feature", "rustc_hir", "rustc_index", + "rustc_infer", "rustc_session", "rustc_span", "rustc_target", - "syntax", ] [[package]] @@ -3813,12 +4000,12 @@ name = "rustc_plugin_impl" version = "0.0.0" dependencies = [ "rustc", + "rustc_ast", "rustc_errors", "rustc_hir", "rustc_lint", "rustc_metadata", "rustc_span", - "syntax", ] [[package]] @@ -3827,12 +4014,13 @@ version = "0.0.0" dependencies = [ "log", "rustc", + "rustc_ast", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_hir", "rustc_span", "rustc_typeck", - "syntax", ] [[package]] @@ -3843,17 +4031,20 @@ dependencies = [ "bitflags", "log", "rustc", + "rustc_ast", "rustc_ast_lowering", + "rustc_ast_pretty", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_expand", "rustc_feature", "rustc_hir", + "rustc_infer", "rustc_metadata", "rustc_session", "rustc_span", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3864,13 +4055,14 @@ dependencies = [ "rls-data", "rls-span", "rustc", + "rustc_ast", + "rustc_ast_pretty", "rustc_codegen_utils", "rustc_data_structures", "rustc_hir", "rustc_parse", "rustc_span", "serde_json", - "syntax", ] [[package]] @@ -3879,6 +4071,7 @@ version = "0.0.0" dependencies = [ "log", "num_cpus", + "rustc_ast", "rustc_data_structures", "rustc_errors", "rustc_feature", @@ -3931,16 +4124,16 @@ checksum = "b725dadae9fabc488df69a287f5a99c5eaf5d10853842a8a3dfac52476f544ee" name = "rustc_traits" version = "0.0.0" dependencies = [ - "chalk-engine", "log", "rustc", + "rustc_ast", "rustc_data_structures", "rustc_hir", + "rustc_infer", "rustc_macros", "rustc_span", "rustc_target", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3951,7 +4144,9 @@ dependencies = [ "rustc", "rustc_data_structures", "rustc_hir", + "rustc_infer", "rustc_span", + "rustc_target", ] [[package]] @@ -3961,14 +4156,16 @@ dependencies = [ "arena", "log", "rustc", + "rustc_ast", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_hir", "rustc_index", + "rustc_infer", "rustc_span", "rustc_target", "smallvec 1.0.0", - "syntax", ] [[package]] @@ -3986,7 +4183,7 @@ version = "0.0.0" dependencies = [ "itertools 0.8.0", "minifier", - "pulldown-cmark 0.5.3", + "pulldown-cmark 0.7.0", "rustc-rayon", "serde", "serde_json", @@ -4040,7 +4237,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.4.11" +version = "1.4.12" dependencies = [ "annotate-snippets", "bytecount", @@ -4056,9 +4253,14 @@ dependencies = [ "lazy_static 1.4.0", "log", "regex", + "rustc-ap-rustc_ast_pretty", + "rustc-ap-rustc_data_structures", + "rustc-ap-rustc_errors", + "rustc-ap-rustc_parse", + "rustc-ap-rustc_session", + "rustc-ap-rustc_span", "rustc-ap-rustc_target", "rustc-ap-syntax", - "rustc-ap-syntax_pos", "rustc-workspace-hack", "rustfmt-config_proc_macro", "serde", @@ -4475,29 +4677,11 @@ dependencies = [ "unicode-xid 0.2.0", ] -[[package]] -name = "syntax" -version = "0.0.0" -dependencies = [ - "log", - "rustc_data_structures", - "rustc_errors", - "rustc_feature", - "rustc_index", - "rustc_lexer", - "rustc_macros", - "rustc_session", - "rustc_span", - "scoped-tls", - "serialize", - "smallvec 1.0.0", -] - [[package]] name = "tar" -version = "0.4.20" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a303ba60a099fcd2aaa646b14d2724591a96a75283e4b7ed3d1a1658909d9ae2" +checksum = "b3196bfbffbba3e57481b6ea32249fbaf590396a52505a2615adbb79d9d826d3" dependencies = [ "filetime", "libc", @@ -4549,17 +4733,6 @@ dependencies = [ "winapi 0.3.8", ] -[[package]] -name = "term_size" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5b9a66db815dcfd2da92db471106457082577c3c278d4138ab3e3b4e189327" -dependencies = [ - "kernel32-sys", - "libc", - "winapi 0.2.8", -] - [[package]] name = "termcolor" version = "1.0.4" @@ -4580,6 +4753,16 @@ dependencies = [ "redox_termios", ] +[[package]] +name = "termize" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" +dependencies = [ + "libc", + "winapi 0.3.8", +] + [[package]] name = "test" version = "0.0.0" @@ -4623,6 +4806,15 @@ dependencies = [ "lazy_static 1.4.0", ] +[[package]] +name = "thread_local" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14" +dependencies = [ + "lazy_static 1.4.0", +] + [[package]] name = "tidy" version = "0.1.0" @@ -4777,7 +4969,7 @@ dependencies = [ "log", "mio", "num_cpus", - "parking_lot", + "parking_lot 0.9.0", "slab", "tokio-executor", "tokio-io", @@ -4976,11 +5168,11 @@ checksum = "535c204ee4d8434478593480b8f86ab45ec9aae0e83c568ca81abf0fd0e88f86" [[package]] name = "unicase" -version = "2.5.1" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e2e6bd1e59e56598518beb94fd6db628ded570326f0a98c679a304bd9f00150" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" dependencies = [ - "version_check 0.1.5", + "version_check", ] [[package]] @@ -5150,12 +5342,6 @@ dependencies = [ "failure", ] -[[package]] -name = "version_check" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" - [[package]] name = "version_check" version = "0.9.1" diff --git a/Cargo.toml b/Cargo.toml index 9d5c27b96d..2f5a708e8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,13 +31,6 @@ exclude = [ "obj", ] -# Curiously, LLVM 7.0 will segfault if compiled with opt-level=3 -# See issue https://github.com/rust-lang/rust/issues/52378 -[profile.release] -opt-level = 2 -[profile.bench] -opt-level = 2 - # These options are controlled from our rustc wrapper script, so turn them off # here and have them controlled elsewhere. [profile.dev] diff --git a/RELEASES.md b/RELEASES.md index 77d0bbe579..36597b1864 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,3 +1,152 @@ +Version 1.43.0 (2020-04-23) +========================== + +Language +-------- +- [Fixed using binary operations with `&{number}` (e.g. `&1.0`) not having + the type inferred correctly.][68129] +- [Attributes such as `#[cfg()]` can now be used on `if` expressions.][69201] + +**Syntax only changes** +- [Allow `type Foo: Ord` syntactically.][69361] +- [Fuse associated and extern items up to defaultness.][69194] +- [Syntactically allow `self` in all `fn` contexts.][68764] +- [Merge `fn` syntax + cleanup item parsing.][68728] +- [`item` macro fragments can be interpolated into `trait`s, `impl`s, and `extern` blocks.][69366] + For example, you may now write: + ```rust + macro_rules! mac_trait { + ($i:item) => { + trait T { $i } + } + } + mac_trait! { + fn foo() {} + } + ``` + +These are still rejected *semantically*, so you will likely receive an error but +these changes can be seen and parsed by macros and +conditional compilation. + + +Compiler +-------- +- [You can now pass multiple lint flags to rustc to override the previous + flags.][67885] For example; `rustc -D unused -A unused-variables` denies + everything in the `unused` lint group except `unused-variables` which + is explicitly allowed. However, passing `rustc -A unused-variables -D unused` denies + everything in the `unused` lint group **including** `unused-variables` since + the allow flag is specified before the deny flag (and therefore overridden). +- [rustc will now prefer your system MinGW libraries over its bundled libraries + if they are available on `windows-gnu`.][67429] +- [rustc now buffers errors/warnings printed in JSON.][69227] + +Libraries +--------- +- [`Arc<[T; N]>`, `Box<[T; N]>`, and `Rc<[T; N]>`, now implement + `TryFrom>`,`TryFrom>`, and `TryFrom>` + respectively.][69538] **Note** These conversions are only available when `N` + is `0..=32`. +- [You can now use associated constants on floats and integers directly, rather + than having to import the module.][68952] e.g. You can now write `u32::MAX` or + `f32::NAN` with no imports. +- [`u8::is_ascii` is now `const`.][68984] +- [`String` now implements `AsMut`.][68742] +- [Added the `primitive` module to `std` and `core`.][67637] This module + reexports Rust's primitive types. This is mainly useful in macros + where you want avoid these types being shadowed. +- [Relaxed some of the trait bounds on `HashMap` and `HashSet`.][67642] +- [`string::FromUtf8Error` now implements `Clone + Eq`.][68738] + +Stabilized APIs +--------------- +- [`Once::is_completed`] +- [`f32::LOG10_2`] +- [`f32::LOG2_10`] +- [`f64::LOG10_2`] +- [`f64::LOG2_10`] +- [`iter::once_with`] + +Cargo +----- +- [You can now set config `[profile]`s in your `.cargo/config`, or through + your environment.][cargo/7823] +- [Cargo will now set `CARGO_BIN_EXE_` pointing to a binary's + executable path when running integration tests or benchmarks.][cargo/7697] + `` is the name of your binary as-is e.g. If you wanted the executable + path for a binary named `my-program`you would use `env!("CARGO_BIN_EXE_my-program")`. + +Misc +---- +- [Certain checks in the `const_err` lint were deemed unrelated to const + evaluation][69185], and have been moved to the `unconditional_panic` and + `arithmetic_overflow` lints. + +Compatibility Notes +------------------- + +- [Having trailing syntax in the `assert!` macro is now a hard error.][69548] This + has been a warning since 1.36.0. +- [Fixed `Self` not having the correctly inferred type.][69340] This incorrectly + led to some instances being accepted, and now correctly emits a hard error. + +[69340]: https://github.com/rust-lang/rust/pull/69340 + +Internal Only +------------- +These changes provide no direct user facing benefits, but represent significant +improvements to the internals and overall performance of `rustc` and +related tools. + +- [All components are now built with `opt-level=3` instead of `2`.][67878] +- [Improved how rustc generates drop code.][67332] +- [Improved performance from `#[inline]`-ing certain hot functions.][69256] +- [traits: preallocate 2 Vecs of known initial size][69022] +- [Avoid exponential behaviour when relating types][68772] +- [Skip `Drop` terminators for enum variants without drop glue][68943] +- [Improve performance of coherence checks][68966] +- [Deduplicate types in the generator witness][68672] +- [Invert control in struct_lint_level.][68725] + +[67332]: https://github.com/rust-lang/rust/pull/67332/ +[67429]: https://github.com/rust-lang/rust/pull/67429/ +[67637]: https://github.com/rust-lang/rust/pull/67637/ +[67642]: https://github.com/rust-lang/rust/pull/67642/ +[67878]: https://github.com/rust-lang/rust/pull/67878/ +[67885]: https://github.com/rust-lang/rust/pull/67885/ +[68129]: https://github.com/rust-lang/rust/pull/68129/ +[68672]: https://github.com/rust-lang/rust/pull/68672/ +[68725]: https://github.com/rust-lang/rust/pull/68725/ +[68728]: https://github.com/rust-lang/rust/pull/68728/ +[68738]: https://github.com/rust-lang/rust/pull/68738/ +[68742]: https://github.com/rust-lang/rust/pull/68742/ +[68764]: https://github.com/rust-lang/rust/pull/68764/ +[68772]: https://github.com/rust-lang/rust/pull/68772/ +[68943]: https://github.com/rust-lang/rust/pull/68943/ +[68952]: https://github.com/rust-lang/rust/pull/68952/ +[68966]: https://github.com/rust-lang/rust/pull/68966/ +[68984]: https://github.com/rust-lang/rust/pull/68984/ +[69022]: https://github.com/rust-lang/rust/pull/69022/ +[69185]: https://github.com/rust-lang/rust/pull/69185/ +[69194]: https://github.com/rust-lang/rust/pull/69194/ +[69201]: https://github.com/rust-lang/rust/pull/69201/ +[69227]: https://github.com/rust-lang/rust/pull/69227/ +[69548]: https://github.com/rust-lang/rust/pull/69548/ +[69256]: https://github.com/rust-lang/rust/pull/69256/ +[69361]: https://github.com/rust-lang/rust/pull/69361/ +[69366]: https://github.com/rust-lang/rust/pull/69366/ +[69538]: https://github.com/rust-lang/rust/pull/69538/ +[cargo/7823]: https://github.com/rust-lang/cargo/pull/7823 +[cargo/7697]: https://github.com/rust-lang/cargo/pull/7697 +[`Once::is_completed`]: https://doc.rust-lang.org/std/sync/struct.Once.html#method.is_completed +[`f32::LOG10_2`]: https://doc.rust-lang.org/std/f32/consts/constant.LOG10_2.html +[`f32::LOG2_10`]: https://doc.rust-lang.org/std/f32/consts/constant.LOG2_10.html +[`f64::LOG10_2`]: https://doc.rust-lang.org/std/f64/consts/constant.LOG10_2.html +[`f64::LOG2_10`]: https://doc.rust-lang.org/std/f64/consts/constant.LOG2_10.html +[`iter::once_with`]: https://doc.rust-lang.org/std/iter/fn.once_with.html + + Version 1.42.0 (2020-03-12) ========================== @@ -71,15 +220,7 @@ Compatibility Notes ------------------- - [`Error::description` has been deprecated, and its use will now produce a warning.][66919] It's recommended to use `Display`/`to_string` instead. -- [`use $crate;` inside macros is now a hard error.][37390] The compiler - emitted forward compatibility warnings since Rust 1.14.0. -- [As previously announced, this release reduces the level of support for - 32-bit Apple targets to tier 3.][apple-32bit-drop]. This means that the - source code is still available to build, but the targets are no longer tested - and no release binary is distributed by the Rust project. Please refer to the - linked blog post for more information. - -[37390]: https://github.com/rust-lang/rust/issues/37390/ + [68253]: https://github.com/rust-lang/rust/pull/68253/ [68348]: https://github.com/rust-lang/rust/pull/68348/ [67935]: https://github.com/rust-lang/rust/pull/67935/ @@ -4846,7 +4987,6 @@ Version 1.11.0 (2016-08-18) Language -------- -* [`cfg_attr` works on `path` attributes](https://github.com/rust-lang/rust/pull/34546) * [Support nested `cfg_attr` attributes](https://github.com/rust-lang/rust/pull/34216) * [Allow statement-generating braced macro invocations at the end of blocks](https://github.com/rust-lang/rust/pull/34436) * [Macros can be expanded inside of trait definitions](https://github.com/rust-lang/rust/pull/34213) @@ -4965,8 +5105,6 @@ Version 1.10.0 (2016-07-07) Language -------- -* [Allow `concat_idents!` in type positions as well as in expression - positions](https://github.com/rust-lang/rust/pull/33735). * [`Copy` types are required to have a trivial implementation of `Clone`](https://github.com/rust-lang/rust/pull/33420). [RFC 1521](https://github.com/rust-lang/rfcs/blob/master/text/1521-copy-clone-semantics.md). * [Single-variant enums support the `#[repr(..)]` attribute](https://github.com/rust-lang/rust/pull/33355). diff --git a/config.toml.example b/config.toml.example index c9e17337ee..ce21b63467 100644 --- a/config.toml.example +++ b/config.toml.example @@ -315,7 +315,7 @@ # `0` - no debug info # `1` - line tables only # `2` - full debug info with variable and type information -# Can be overriden for specific subsets of Rust code (rustc, std or tools). +# Can be overridden for specific subsets of Rust code (rustc, std or tools). # Debuginfo for tests run with compiletest is not controlled by this option # and needs to be enabled separately with `debuginfo-level-tests`. #debuginfo-level = if debug { 2 } else { 0 } @@ -395,6 +395,15 @@ # rustc to execute. #lld = false +# Indicates whether LLD will be used to link Rust crates during bootstrap on +# supported platforms. The LLD from the bootstrap distribution will be used +# and not the LLD compiled during the bootstrap. +# +# LLD will not be used if we're cross linking or running tests. +# +# Explicitly setting the linker for a target will override this option. +#use-lld = false + # Indicates whether some LLVM tools, like llvm-objdump, will be made available in the # sysroot. #llvm-tools = false @@ -435,6 +444,10 @@ # Use LLVM libunwind as the implementation for Rust's unwinder. #llvm-libunwind = false +# Enable Windows Control Flow Guard checks in the standard library. +# This only applies from stage 1 onwards, and only for Windows targets. +#control-flow-guard = false + # ============================================================================= # Options for specific targets # @@ -463,6 +476,7 @@ # Linker to be used to link Rust code. Note that the # default value is platform specific, and if not specified it may also depend on # what platform is crossing to what platform. +# Setting this will override the `use-lld` option for Rust code. #linker = "cc" # Path to the `llvm-config` binary of the installation of a custom LLVM to link diff --git a/git-commit-hash b/git-commit-hash index 1a947ee947..5dad6a9f56 100644 --- a/git-commit-hash +++ b/git-commit-hash @@ -1 +1 @@ -b8cedc00407a4c56a3bda1ed605c6fc166655447 \ No newline at end of file +4fb7144ed159f94491249e86d5bbd033b5d60550 \ No newline at end of file diff --git a/src/bootstrap/bin/rustc.rs b/src/bootstrap/bin/rustc.rs index a34ec44566..daa030c59d 100644 --- a/src/bootstrap/bin/rustc.rs +++ b/src/bootstrap/bin/rustc.rs @@ -47,7 +47,7 @@ fn main() { }; let stage = env::var("RUSTC_STAGE").expect("RUSTC_STAGE was not set"); let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); - let on_fail = env::var_os("RUSTC_ON_FAIL").map(|of| Command::new(of)); + let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new); let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); @@ -64,7 +64,7 @@ fn main() { if let Some(crate_name) = crate_name { if let Some(target) = env::var_os("RUSTC_TIME") { if target == "all" - || target.into_string().unwrap().split(",").any(|c| c.trim() == crate_name) + || target.into_string().unwrap().split(',').any(|c| c.trim() == crate_name) { cmd.arg("-Ztime"); } @@ -134,6 +134,11 @@ fn main() { cmd.arg(format!("-Clinker={}", host_linker)); } + // Override linker flavor if necessary. + if let Ok(host_linker_flavor) = env::var("RUSTC_HOST_LINKER_FLAVOR") { + cmd.arg(format!("-Clinker-flavor={}", host_linker_flavor)); + } + if let Ok(s) = env::var("RUSTC_HOST_CRT_STATIC") { if s == "true" { cmd.arg("-C").arg("target-feature=+crt-static"); @@ -189,7 +194,7 @@ fn main() { crate_name, is_test, dur.as_secs(), - dur.subsec_nanos() / 1_000_000 + dur.subsec_millis() ); match status.code() { diff --git a/src/bootstrap/bin/rustdoc.rs b/src/bootstrap/bin/rustdoc.rs index 8c8b33a4e4..04345867bf 100644 --- a/src/bootstrap/bin/rustdoc.rs +++ b/src/bootstrap/bin/rustdoc.rs @@ -61,7 +61,7 @@ fn main() { } // Needed to be able to run all rustdoc tests. - if let Some(_) = env::var_os("RUSTDOC_GENERATE_REDIRECT_PAGES") { + if env::var_os("RUSTDOC_GENERATE_REDIRECT_PAGES").is_some() { // This "unstable-options" can be removed when `--generate-redirect-pages` is stabilized if !has_unstable { cmd.arg("-Z").arg("unstable-options"); diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 6737086f6e..50e1726240 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -80,7 +80,7 @@ def _download(path, url, probably_big, verbose, exception): option = "-s" run(["curl", option, "-y", "30", "-Y", "10", # timeout if speed is < 10 bytes/sec for > 30 seconds - "--connect-timeout", "30", # timeout if cannot connect within 30 seconds + "--connect-timeout", "30", # timeout if cannot connect within 30 seconds "--retry", "3", "-Sf", "-o", path, url], verbose=verbose, exception=exception) @@ -332,7 +332,6 @@ class RustBuild(object): self.use_vendored_sources = '' self.verbose = False - def download_stage0(self): """Fetch the build system for Rust, written in Rust @@ -351,7 +350,7 @@ class RustBuild(object): try: with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_path = temp_file.name - with tarfile.open(temp_path, "w:xz") as tar: + with tarfile.open(temp_path, "w:xz"): pass return True except tarfile.CompressionError: @@ -397,7 +396,7 @@ class RustBuild(object): if self.rustfmt() and self.rustfmt().startswith(self.bin_root()) and ( not os.path.exists(self.rustfmt()) - or self.program_out_of_date(self.rustfmt_stamp()) + or self.program_out_of_date(self.rustfmt_stamp(), self.rustfmt_channel) ): if rustfmt_channel: tarball_suffix = '.tar.xz' if support_xz() else '.tar.gz' @@ -407,7 +406,7 @@ class RustBuild(object): self.fix_executable("{}/bin/rustfmt".format(self.bin_root())) self.fix_executable("{}/bin/cargo-fmt".format(self.bin_root())) with output(self.rustfmt_stamp()) as rustfmt_stamp: - rustfmt_stamp.write(self.date) + rustfmt_stamp.write(self.date + self.rustfmt_channel) def _download_stage0_helper(self, filename, pattern, tarball_suffix, date=None): if date is None: @@ -521,12 +520,12 @@ class RustBuild(object): """ return os.path.join(self.bin_root(), '.rustfmt-stamp') - def program_out_of_date(self, stamp_path): + def program_out_of_date(self, stamp_path, extra=""): """Check if the given program stamp is out of date""" if not os.path.exists(stamp_path) or self.clean: return True with open(stamp_path, 'r') as stamp: - return self.date != stamp.read() + return (self.date + extra) != stamp.read() def bin_root(self): """Return the binary root directory @@ -825,7 +824,7 @@ class RustBuild(object): if not os.path.exists(vendor_dir): print('error: vendoring required, but vendor directory does not exist.') print(' Run `cargo vendor` without sudo to initialize the ' - 'vendor directory.') + 'vendor directory.') raise Exception("{} not found".format(vendor_dir)) if self.use_vendored_sources: @@ -839,7 +838,7 @@ class RustBuild(object): "\n" "[source.vendored-sources]\n" "directory = '{}/vendor'\n" - .format(self.rust_root)) + .format(self.rust_root)) else: if os.path.exists('.cargo'): shutil.rmtree('.cargo') diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index d9c894aa9c..eb0199fd02 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -510,7 +510,7 @@ impl<'a> Builder<'a> { Subcommand::Format { .. } | Subcommand::Clean { .. } => panic!(), }; - let builder = Builder { + Builder { build, top_stage: build.config.stage.unwrap_or(2), kind, @@ -518,9 +518,7 @@ impl<'a> Builder<'a> { stack: RefCell::new(Vec::new()), time_spent_on_dependencies: Cell::new(Duration::new(0, 0)), paths: paths.to_owned(), - }; - - builder + } } pub fn execute_cli(&self) { @@ -694,7 +692,7 @@ impl<'a> Builder<'a> { cmd.env_remove("MAKEFLAGS"); cmd.env_remove("MFLAGS"); - if let Some(linker) = self.linker(compiler.host) { + if let Some(linker) = self.linker(compiler.host, true) { cmd.env("RUSTC_TARGET_LINKER", linker); } cmd @@ -727,7 +725,11 @@ impl<'a> Builder<'a> { self.clear_if_dirty(&my_out, &rustdoc); } - cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd).arg("-Zconfig-profile"); + cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd); + + if !self.local_rebuild { + cargo.arg("-Zconfig-profile"); + } let profile_var = |name: &str| { let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" }; @@ -753,13 +755,12 @@ impl<'a> Builder<'a> { cargo.env("RUST_CHECK", "1"); } - let stage; - if compiler.stage == 0 && self.local_rebuild { + let stage = if compiler.stage == 0 && self.local_rebuild { // Assume the local-rebuild rustc already has stage1 features. - stage = 1; + 1 } else { - stage = compiler.stage; - } + compiler.stage + }; let mut rustflags = Rustflags::new(&target); if stage != 0 { @@ -850,7 +851,13 @@ impl<'a> Builder<'a> { rustflags.arg("-Zforce-unstable-if-unmarked"); } - rustflags.arg("-Zexternal-macro-backtrace"); + // cfg(bootstrap): the flag was renamed from `-Zexternal-macro-backtrace` + // to `-Zmacro-backtrace`, keep only the latter after beta promotion. + if stage == 0 { + rustflags.arg("-Zexternal-macro-backtrace"); + } else { + rustflags.arg("-Zmacro-backtrace"); + } let want_rustdoc = self.doc_tests != DocTests::No; @@ -949,10 +956,31 @@ impl<'a> Builder<'a> { } } - if let Some(host_linker) = self.linker(compiler.host) { + // FIXME: Don't use LLD if we're compiling libtest, since it fails to link it. + // See https://github.com/rust-lang/rust/issues/68647. + let can_use_lld = mode != Mode::Std; + + // FIXME: The beta compiler doesn't pick the `lld-link` flavor for `*-pc-windows-msvc` + // Remove `RUSTC_HOST_LINKER_FLAVOR` when this is fixed + let lld_linker_flavor = |linker: &Path, target: Interned| { + compiler.stage == 0 + && linker.file_name() == Some(OsStr::new("rust-lld")) + && target.contains("pc-windows-msvc") + }; + + if let Some(host_linker) = self.linker(compiler.host, can_use_lld) { + if lld_linker_flavor(host_linker, compiler.host) { + cargo.env("RUSTC_HOST_LINKER_FLAVOR", "lld-link"); + } + cargo.env("RUSTC_HOST_LINKER", host_linker); } - if let Some(target_linker) = self.linker(target) { + + if let Some(target_linker) = self.linker(target, can_use_lld) { + if lld_linker_flavor(target_linker, target) { + rustflags.arg("-Clinker-flavor=lld-link"); + } + let target = crate::envify(&target); cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker); } @@ -1111,6 +1139,20 @@ impl<'a> Builder<'a> { ); } + // If Control Flow Guard is enabled, pass the `control_flow_guard=checks` flag to rustc + // when compiling the standard library, since this might be linked into the final outputs + // produced by rustc. Since this mitigation is only available on Windows, only enable it + // for the standard library in case the compiler is run on a non-Windows platform. + // This is not needed for stage 0 artifacts because these will only be used for building + // the stage 1 compiler. + if cfg!(windows) + && mode == Mode::Std + && self.config.control_flow_guard + && compiler.stage >= 1 + { + rustflags.arg("-Zcontrol_flow_guard=checks"); + } + // For `cargo doc` invocations, make rustdoc print the Rust version into the docs cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version()); @@ -1252,12 +1294,7 @@ impl<'a> Builder<'a> { }; if self.config.print_step_timings && dur > Duration::from_millis(100) { - println!( - "[TIMING] {:?} -- {}.{:03}", - step, - dur.as_secs(), - dur.subsec_nanos() / 1_000_000 - ); + println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis()); } { @@ -1302,7 +1339,7 @@ impl Rustflags { fn arg(&mut self, arg: &str) -> &mut Self { assert_eq!(arg.split_whitespace().count(), 1); - if self.0.len() > 0 { + if !self.0.is_empty() { self.0.push_str(" "); } self.0.push_str(arg); diff --git a/src/bootstrap/builder/tests.rs b/src/bootstrap/builder/tests.rs index 5fefb97286..cca8ab80c9 100644 --- a/src/bootstrap/builder/tests.rs +++ b/src/bootstrap/builder/tests.rs @@ -19,7 +19,6 @@ fn configure(host: &[&str], target: &[&str]) -> Config { config.out = dir; config.build = INTERNER.intern_str("A"); config.hosts = vec![config.build] - .clone() .into_iter() .chain(host.iter().map(|s| INTERNER.intern_str(s))) .collect::>(); diff --git a/src/bootstrap/channel.rs b/src/bootstrap/channel.rs index 38810237ef..504cba4557 100644 --- a/src/bootstrap/channel.rs +++ b/src/bootstrap/channel.rs @@ -13,7 +13,7 @@ use build_helper::output; use crate::Build; // The version number -pub const CFG_RELEASE_NUM: &str = "1.42.0"; +pub const CFG_RELEASE_NUM: &str = "1.43.0"; pub struct GitInfo { inner: Option, diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index eced03506a..65a00db339 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -18,7 +18,6 @@ use std::str; use build_helper::{output, t, up_to_date}; use filetime::FileTime; use serde::Deserialize; -use serde_json; use crate::builder::Cargo; use crate::dist; @@ -142,14 +141,15 @@ fn copy_third_party_objects( copy_and_stamp(&srcdir, "crt1.o"); } - // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx. + // Copies libunwind.a compiled to be linked with x86_64-fortanix-unknown-sgx. // // This target needs to be linked to Fortanix's port of llvm's libunwind. // libunwind requires support for rwlock and printing to stderr, // which is provided by std for this target. if target == "x86_64-fortanix-unknown-sgx" { let src_path_env = "X86_FORTANIX_SGX_LIBS"; - let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env)); + let src = + env::var(src_path_env).unwrap_or_else(|_| panic!("{} not found in env", src_path_env)); copy_and_stamp(Path::new(&src), "libunwind.a"); } @@ -361,7 +361,7 @@ impl Step for StartupObjects { ); } - let target = sysroot_dir.join(file.to_string() + ".o"); + let target = sysroot_dir.join((*file).to_string() + ".o"); builder.copy(dst_file, &target); target_deps.push(target); } @@ -515,7 +515,7 @@ pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interne .env("CFG_VERSION", builder.rust_version()) .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default()); - let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib")); + let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib")); cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative); if let Some(ref ver_date) = builder.rust_info.commit_date() { @@ -843,11 +843,11 @@ pub fn run_cargo( }; for filename in filenames { // Skip files like executables - if !filename.ends_with(".rlib") - && !filename.ends_with(".lib") - && !filename.ends_with(".a") - && !is_dylib(&filename) - && !(is_check && filename.ends_with(".rmeta")) + if !(filename.ends_with(".rlib") + || filename.ends_with(".lib") + || filename.ends_with(".a") + || is_dylib(&filename) + || (is_check && filename.ends_with(".rmeta"))) { continue; } @@ -905,7 +905,7 @@ pub fn run_cargo( for (prefix, extension, expected_len) in toplevel { let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| { filename.starts_with(&prefix[..]) - && filename[prefix.len()..].starts_with("-") + && filename[prefix.len()..].starts_with('-') && filename.ends_with(&extension[..]) && meta.len() == expected_len }); diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 110c8b844d..56164b74f3 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -16,7 +16,6 @@ use crate::flags::Flags; pub use crate::flags::Subcommand; use build_helper::t; use serde::Deserialize; -use toml; /// Global configuration for the entire build and/or bootstrap. /// @@ -83,6 +82,7 @@ pub struct Config { pub llvm_use_linker: Option, pub llvm_allow_old_toolchain: Option, + pub use_lld: bool, pub lld_enabled: bool, pub lldb_enabled: bool, pub llvm_tools_enabled: bool, @@ -116,6 +116,7 @@ pub struct Config { pub targets: Vec>, pub local_rebuild: bool, pub jemalloc: bool, + pub control_flow_guard: bool, // dist misc pub dist_sign_folder: Option, @@ -176,6 +177,15 @@ pub struct Target { pub no_std: bool, } +impl Target { + pub fn from_triple(triple: &str) -> Self { + let mut target: Self = Default::default(); + if triple.contains("-none") || triple.contains("nvptx") { + target.no_std = true; + } + target + } +} /// Structure of the `config.toml` file that configuration is read from. /// /// This structure uses `Decodable` to automatically decode a TOML configuration @@ -322,6 +332,7 @@ struct Rust { save_toolstates: Option, codegen_backends: Option>, lld: Option, + use_lld: Option, llvm_tools: Option, lldb: Option, deny_warnings: Option, @@ -332,6 +343,7 @@ struct Rust { jemalloc: Option, test_compare_mode: Option, llvm_libunwind: Option, + control_flow_guard: Option, } /// TOML representation of how each build target is configured. @@ -350,6 +362,7 @@ struct TomlTarget { musl_root: Option, wasi_root: Option, qemu_rootfs: Option, + no_std: Option, } impl Config { @@ -440,7 +453,7 @@ impl Config { } } }) - .unwrap_or_else(|| TomlConfig::default()); + .unwrap_or_else(TomlConfig::default); let build = toml.build.clone().unwrap_or_default(); // set by bootstrap.py @@ -539,7 +552,7 @@ impl Config { config.llvm_ldflags = llvm.ldflags.clone(); set(&mut config.llvm_use_libcxx, llvm.use_libcxx); config.llvm_use_linker = llvm.use_linker.clone(); - config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.clone(); + config.llvm_allow_old_toolchain = llvm.allow_old_toolchain; } if let Some(ref rust) = toml.rust { @@ -566,6 +579,7 @@ impl Config { if let Some(true) = rust.incremental { config.incremental = true; } + set(&mut config.use_lld, rust.use_lld); set(&mut config.lld_enabled, rust.lld); set(&mut config.lldb_enabled, rust.lldb); set(&mut config.llvm_tools_enabled, rust.llvm_tools); @@ -578,6 +592,7 @@ impl Config { set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir); config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit; set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo); + set(&mut config.control_flow_guard, rust.control_flow_guard); if let Some(ref backends) = rust.codegen_backends { config.rust_codegen_backends = @@ -590,7 +605,7 @@ impl Config { if let Some(ref t) = toml.target { for (triple, cfg) in t { - let mut target = Target::default(); + let mut target = Target::from_triple(triple); if let Some(ref s) = cfg.llvm_config { target.llvm_config = Some(config.src.join(s)); @@ -601,12 +616,15 @@ impl Config { if let Some(ref s) = cfg.android_ndk { target.ndk = Some(config.src.join(s)); } + if let Some(s) = cfg.no_std { + target.no_std = s; + } target.cc = cfg.cc.clone().map(PathBuf::from); target.cxx = cfg.cxx.clone().map(PathBuf::from); target.ar = cfg.ar.clone().map(PathBuf::from); target.ranlib = cfg.ranlib.clone().map(PathBuf::from); target.linker = cfg.linker.clone().map(PathBuf::from); - target.crt_static = cfg.crt_static.clone(); + target.crt_static = cfg.crt_static; target.musl_root = cfg.musl_root.clone().map(PathBuf::from); target.wasi_root = cfg.wasi_root.clone().map(PathBuf::from); target.qemu_rootfs = cfg.qemu_rootfs.clone().map(PathBuf::from); diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index 7cfc5385e2..2a46c563d1 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -60,10 +60,11 @@ o("lld", "rust.lld", "build lld") o("lldb", "rust.lldb", "build lldb") o("missing-tools", "dist.missing-tools", "allow failures when building tools") o("use-libcxx", "llvm.use-libcxx", "build LLVM with libc++") +o("control-flow-guard", "rust.control-flow-guard", "Enable Control Flow Guard") -o("cflags", "llvm.cflags", "build LLVM with these extra compiler flags") -o("cxxflags", "llvm.cxxflags", "build LLVM with these extra compiler flags") -o("ldflags", "llvm.ldflags", "build LLVM with these extra linker flags") +v("llvm-cflags", "llvm.cflags", "build LLVM with these extra compiler flags") +v("llvm-cxxflags", "llvm.cxxflags", "build LLVM with these extra compiler flags") +v("llvm-ldflags", "llvm.ldflags", "build LLVM with these extra linker flags") o("llvm-libunwind", "rust.llvm-libunwind", "use LLVM libunwind") @@ -392,11 +393,12 @@ for target in configured_targets: def is_number(value): - try: - float(value) - return True - except ValueError: - return False + try: + float(value) + return True + except ValueError: + return False + # Here we walk through the constructed configuration we have from the parsed # command line arguments. We then apply each piece of configuration by diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 8d13df3ee2..8215211ea1 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -105,6 +105,7 @@ impl Step for Docs { t!(fs::create_dir_all(&dst)); let src = builder.doc_out(host); builder.cp_r(&src, &dst); + builder.install(&builder.src.join("src/doc/robots.txt"), &dst, 0o644); let mut cmd = rust_installer(builder); cmd.arg("generate") @@ -233,7 +234,14 @@ fn make_win_dist( } } - let target_tools = ["gcc.exe", "ld.exe", "dlltool.exe", "libwinpthread-1.dll"]; + let compiler = if target_triple == "i686-pc-windows-gnu" { + "i686-w64-mingw32-gcc.exe" + } else if target_triple == "x86_64-pc-windows-gnu" { + "x86_64-w64-mingw32-gcc.exe" + } else { + "gcc.exe" + }; + let target_tools = [compiler, "ld.exe", "dlltool.exe", "libwinpthread-1.dll"]; let mut rustc_dlls = vec!["libwinpthread-1.dll"]; if target_triple.starts_with("i686-") { rustc_dlls.push("libgcc_s_dw2-1.dll"); @@ -827,7 +835,7 @@ impl Step for Analysis { assert!(builder.config.extended); let name = pkgname(builder, "rust-analysis"); - if &compiler.host != builder.config.build { + if compiler.host != builder.config.build { return distdir(builder).join(format!("{}-{}.tar.gz", name, target)); } @@ -876,7 +884,7 @@ fn copy_src_dirs(builder: &Builder<'_>, src_dirs: &[&str], exclude_dirs: &[&str] Some(path) => path, None => return false, }; - if spath.ends_with("~") || spath.ends_with(".pyc") { + if spath.ends_with('~') || spath.ends_with(".pyc") { return false; } @@ -994,8 +1002,6 @@ impl Step for Src { "src/tools/rustc-std-workspace-core", "src/tools/rustc-std-workspace-alloc", "src/tools/rustc-std-workspace-std", - "src/librustc", - "src/libsyntax", ]; copy_src_dirs(builder, &std_src_dirs[..], &[], &dst_src); diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index 204056598d..b0d9a5b946 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -560,7 +560,7 @@ impl Step for Rustdoc { builder.ensure(Rustc { stage, target }); // Build rustdoc. - builder.ensure(tool::Rustdoc { compiler: compiler }); + builder.ensure(tool::Rustdoc { compiler }); // Symlink compiler docs to the output directory of rustdoc documentation. let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target).join("doc"); diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index 2101ef27f9..0b2ab6bbbc 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -33,7 +33,7 @@ pub struct Flags { pub rustc_error_format: Option, pub dry_run: bool, - // This overrides the deny-warnings configuation option, + // This overrides the deny-warnings configuration option, // which passes -Dwarnings to the compiler invocations. // // true => deny, false => warn @@ -571,7 +571,7 @@ fn split(s: &[String]) -> Vec { } fn parse_deny_warnings(matches: &getopts::Matches) -> Option { - match matches.opt_str("warnings").as_ref().map(|v| v.as_str()) { + match matches.opt_str("warnings").as_deref() { Some("deny") => Some(true), Some("warn") => Some(false), Some(value) => { diff --git a/src/bootstrap/format.rs b/src/bootstrap/format.rs index 6e5e3fe07e..a4acb14ee4 100644 --- a/src/bootstrap/format.rs +++ b/src/bootstrap/format.rs @@ -1,7 +1,7 @@ //! Runs rustfmt on the repository. use crate::Build; -use build_helper::t; +use build_helper::{output, t}; use ignore::WalkBuilder; use std::path::Path; use std::process::Command; @@ -53,6 +53,17 @@ pub fn format(build: &Build, check: bool) { for ignore in rustfmt_config.ignore { ignore_fmt.add(&format!("!{}", ignore)).expect(&ignore); } + let untracked_paths_output = output( + Command::new("git").arg("status").arg("--porcelain").arg("--untracked-files=normal"), + ); + let untracked_paths = untracked_paths_output + .lines() + .filter(|entry| entry.starts_with("??")) + .map(|entry| entry.split(" ").nth(1).expect("every git status entry should list a path")); + for untracked_path in untracked_paths { + eprintln!("skip untracked path {} during rustfmt invocations", untracked_path); + ignore_fmt.add(&format!("!{}", untracked_path)).expect(&untracked_path); + } let ignore_fmt = ignore_fmt.build().unwrap(); let rustfmt_path = build.config.initial_rustfmt.as_ref().unwrap_or_else(|| { diff --git a/src/bootstrap/install.rs b/src/bootstrap/install.rs index f8734ebdf4..6549262811 100644 --- a/src/bootstrap/install.rs +++ b/src/bootstrap/install.rs @@ -126,9 +126,8 @@ fn add_destdir(path: &Path, destdir: &Option) -> PathBuf { None => return path.to_path_buf(), }; for part in path.components() { - match part { - Component::Normal(s) => ret.push(s), - _ => {} + if let Component::Normal(s) = part { + ret.push(s) } } ret diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 1fee3fd9ac..a476d25f10 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -103,7 +103,6 @@ //! More documentation can be found in each respective module below, and you can //! also check out the `src/bootstrap/README.md` file for more information. -#![feature(core_intrinsics)] #![feature(drain_filter)] use std::cell::{Cell, RefCell}; @@ -239,9 +238,10 @@ pub struct Build { hosts: Vec>, targets: Vec>, - // Stage 0 (downloaded) compiler and cargo or their local rust equivalents + // Stage 0 (downloaded) compiler, lld and cargo or their local rust equivalents initial_rustc: PathBuf, initial_cargo: PathBuf, + initial_lld: PathBuf, // Runtime state filled in later on // C/C++ compilers and archiver for all targets @@ -343,9 +343,18 @@ impl Build { // we always try to use git for LLVM builds let in_tree_llvm_info = channel::GitInfo::new(false, &src.join("src/llvm-project")); + let initial_sysroot = config.initial_rustc.parent().unwrap().parent().unwrap(); + let initial_lld = initial_sysroot + .join("lib") + .join("rustlib") + .join(config.build) + .join("bin") + .join("rust-lld"); + let mut build = Build { initial_rustc: config.initial_rustc.clone(), initial_cargo: config.initial_cargo.clone(), + initial_lld, local_rebuild: config.local_rebuild, fail_fast: config.cmd.fail_fast(), doc_tests: config.cmd.doc_tests(), @@ -444,7 +453,7 @@ impl Build { builder.execute_cli(); } else { let builder = builder::Builder::new(&self); - let _ = builder.execute_cli(); + builder.execute_cli(); } // Check for postponed failures from `test --no-fail-fast`. @@ -810,7 +819,7 @@ impl Build { } /// Returns the path to the linker for the given target if it needs to be overridden. - fn linker(&self, target: Interned) -> Option<&Path> { + fn linker(&self, target: Interned, can_use_lld: bool) -> Option<&Path> { if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.as_ref()) { Some(linker) @@ -819,6 +828,8 @@ impl Build { && !target.contains("msvc") { Some(self.cc(target)) + } else if can_use_lld && self.config.use_lld && self.build == target { + Some(&self.initial_lld) } else { None } @@ -839,7 +850,7 @@ impl Build { .target_config .get(&target) .and_then(|t| t.musl_root.as_ref()) - .or(self.config.musl_root.as_ref()) + .or_else(|| self.config.musl_root.as_ref()) .map(|p| &**p) } @@ -1026,7 +1037,7 @@ impl Build { } fn llvm_link_tools_dynamically(&self, target: Interned) -> bool { - (target.contains("linux-gnu") || target.contains("apple-darwin")) + target.contains("linux-gnu") || target.contains("apple-darwin") } /// Returns the `version` string associated with this compiler for Rust diff --git a/src/bootstrap/metadata.rs b/src/bootstrap/metadata.rs index 8a26adc7ed..292aa3b1e2 100644 --- a/src/bootstrap/metadata.rs +++ b/src/bootstrap/metadata.rs @@ -5,7 +5,6 @@ use std::process::Command; use build_helper::output; use serde::Deserialize; -use serde_json; use crate::cache::INTERNER; use crate::{Build, Crate}; diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index a796685f9d..c22c2a336f 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -15,8 +15,6 @@ use std::path::{Path, PathBuf}; use std::process::Command; use build_helper::{output, t}; -use cc; -use cmake; use crate::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::cache::Interned; @@ -205,7 +203,7 @@ impl Step for Llvm { cfg.define("LLVM_ENABLE_LIBXML2", "OFF"); } - if enabled_llvm_projects.len() > 0 { + if !enabled_llvm_projects.is_empty() { enabled_llvm_projects.sort(); enabled_llvm_projects.dedup(); cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";")); @@ -243,12 +241,8 @@ impl Step for Llvm { cfg.define("LLVM_VERSION_SUFFIX", suffix); } } else { - let mut default_suffix = - format!("-rust-{}-{}", channel::CFG_RELEASE_NUM, builder.config.channel,); - if let Some(sha) = llvm_info.sha_short() { - default_suffix.push_str("-"); - default_suffix.push_str(sha); - } + let default_suffix = + format!("-rust-{}-{}", channel::CFG_RELEASE_NUM, builder.config.channel); cfg.define("LLVM_VERSION_SUFFIX", default_suffix); } @@ -580,7 +574,7 @@ impl Step for Sanitizers { } let out_dir = builder.native_dir(self.target).join("sanitizers"); - let runtimes = supported_sanitizers(&out_dir, self.target); + let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel); if runtimes.is_empty() { return runtimes; } @@ -647,7 +641,11 @@ pub struct SanitizerRuntime { } /// Returns sanitizers available on a given target. -fn supported_sanitizers(out_dir: &Path, target: Interned) -> Vec { +fn supported_sanitizers( + out_dir: &Path, + target: Interned, + channel: &str, +) -> Vec { let mut result = Vec::new(); match &*target { "x86_64-apple-darwin" => { @@ -656,7 +654,7 @@ fn supported_sanitizers(out_dir: &Path, target: Interned) -> Vec) -> Vec) -> Vec) -> Vec, mode: &'static str, suite: &'static str, - path: Option<&'static str>, + path: &'static str, compare_mode: Option<&'static str>, } @@ -949,7 +951,7 @@ impl Step for Compiletest { let suite = self.suite; // Path for test suite - let suite_path = self.path.unwrap_or(""); + let suite_path = self.path; // Skip codegen tests if they aren't enabled in configuration. if !builder.config.codegen_tests && suite == "codegen" { @@ -1035,7 +1037,8 @@ impl Step for Compiletest { flags.push("-Zunstable-options".to_string()); flags.push(builder.config.cmd.rustc_args().join(" ")); - if let Some(linker) = builder.linker(target) { + // Don't use LLD here since we want to test that rustc finds and uses a linker by itself. + if let Some(linker) = builder.linker(target, false) { cmd.arg("--linker").arg(linker); } @@ -1149,7 +1152,6 @@ impl Step for Compiletest { // requires that a C++ compiler was configured which isn't always the case. if !builder.config.dry_run && suite == "run-make-fulldeps" { let llvm_components = output(Command::new(&llvm_config).arg("--components")); - let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags")); cmd.arg("--cc") .arg(builder.cc(target)) .arg("--cxx") @@ -1157,9 +1159,7 @@ impl Step for Compiletest { .arg("--cflags") .arg(builder.cflags(target, GitRepo::Rustc).join(" ")) .arg("--llvm-components") - .arg(llvm_components.trim()) - .arg("--llvm-cxxflags") - .arg(llvm_cxxflags.trim()); + .arg(llvm_components.trim()); if let Some(ar) = builder.ar(target) { cmd.arg("--ar").arg(ar); } @@ -1197,8 +1197,6 @@ impl Step for Compiletest { .arg("--cflags") .arg("") .arg("--llvm-components") - .arg("") - .arg("--llvm-cxxflags") .arg(""); } @@ -1268,15 +1266,15 @@ impl Step for Compiletest { } } -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -struct DocTest { +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct BookTest { compiler: Compiler, - path: &'static str, + path: PathBuf, name: &'static str, is_ext_doc: bool, } -impl Step for DocTest { +impl Step for BookTest { type Output = (); const ONLY_HOSTS: bool = true; @@ -1284,12 +1282,59 @@ impl Step for DocTest { run.never() } - /// Runs `rustdoc --test` for all documentation in `src/doc`. + /// Runs the documentation tests for a book in `src/doc`. /// - /// This will run all tests in our markdown documentation (e.g., the book) - /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to - /// `compiler`. + /// This uses the `rustdoc` that sits next to `compiler`. fn run(self, builder: &Builder<'_>) { + // External docs are different from local because: + // - Some books need pre-processing by mdbook before being tested. + // - They need to save their state to toolstate. + // - They are only tested on the "checktools" builders. + // + // The local docs are tested by default, and we don't want to pay the + // cost of building mdbook, so they use `rustdoc --test` directly. + // Also, the unstable book is special because SUMMARY.md is generated, + // so it is easier to just run `rustdoc` on its files. + if self.is_ext_doc { + self.run_ext_doc(builder); + } else { + self.run_local_doc(builder); + } + } +} + +impl BookTest { + /// This runs the equivalent of `mdbook test` (via the rustbook wrapper) + /// which in turn runs `rustdoc --test` on each file in the book. + fn run_ext_doc(self, builder: &Builder<'_>) { + let compiler = self.compiler; + + builder.ensure(compile::Std { compiler, target: compiler.host }); + + // mdbook just executes a binary named "rustdoc", so we need to update + // PATH so that it points to our rustdoc. + let mut rustdoc_path = builder.rustdoc(compiler); + rustdoc_path.pop(); + let old_path = env::var_os("PATH").unwrap_or_default(); + let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path))) + .expect("could not add rustdoc to PATH"); + + let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook); + let path = builder.src.join(&self.path); + rustbook_cmd.env("PATH", new_path).arg("test").arg(path); + builder.add_rust_test_threads(&mut rustbook_cmd); + builder.info(&format!("Testing rustbook {}", self.path.display())); + let _time = util::timeit(&builder); + let toolstate = if try_run(builder, &mut rustbook_cmd) { + ToolState::TestPass + } else { + ToolState::TestFail + }; + builder.save_toolstate(self.name, toolstate); + } + + /// This runs `rustdoc --test` on all `.md` files in the path. + fn run_local_doc(self, builder: &Builder<'_>) { let compiler = self.compiler; builder.ensure(compile::Std { compiler, target: compiler.host }); @@ -1298,7 +1343,6 @@ impl Step for DocTest { // tests for all files that end in `*.md` let mut stack = vec![builder.src.join(self.path)]; let _time = util::timeit(&builder); - let mut files = Vec::new(); while let Some(p) = stack.pop() { if p.is_dir() { @@ -1310,25 +1354,13 @@ impl Step for DocTest { continue; } - // The nostarch directory in the book is for no starch, and so isn't - // guaranteed to builder. We don't care if it doesn't build, so skip it. - if p.to_str().map_or(false, |p| p.contains("nostarch")) { - continue; - } - files.push(p); } files.sort(); - let mut toolstate = ToolState::TestPass; for file in files { - if !markdown_test(builder, compiler, &file) { - toolstate = ToolState::TestFail; - } - } - if self.is_ext_doc { - builder.save_toolstate(self.name, toolstate); + markdown_test(builder, compiler, &file); } } } @@ -1357,9 +1389,9 @@ macro_rules! test_book { } fn run(self, builder: &Builder<'_>) { - builder.ensure(DocTest { + builder.ensure(BookTest { compiler: self.compiler, - path: $path, + path: PathBuf::from($path), name: $book_name, is_ext_doc: !$default, }); @@ -1429,13 +1461,10 @@ impl Step for ErrorIndex { } fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool { - match fs::read_to_string(markdown) { - Ok(contents) => { - if !contents.contains("```") { - return true; - } + if let Ok(contents) = fs::read_to_string(markdown) { + if !contents.contains("```") { + return true; } - Err(_) => {} } builder.info(&format!("doc tests for: {}", markdown.display())); @@ -1464,7 +1493,7 @@ impl Step for RustcGuide { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("src/doc/rustc-guide") + run.path("src/doc/rustc-dev-guide") } fn make_run(run: RunConfig<'_>) { @@ -1472,14 +1501,14 @@ impl Step for RustcGuide { } fn run(self, builder: &Builder<'_>) { - let src = builder.src.join("src/doc/rustc-guide"); + let src = builder.src.join("src/doc/rustc-dev-guide"); let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook); let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) { ToolState::TestPass } else { ToolState::TestFail }; - builder.save_toolstate("rustc-guide", toolstate); + builder.save_toolstate("rustc-dev-guide", toolstate); } } diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 7f24768a4f..67e0ed5c58 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -234,7 +234,7 @@ pub fn prepare_tool_cargo( cargo.env("RUSTC_EXTERNAL_TOOL", "1"); } - let mut features = extra_features.iter().cloned().collect::>(); + let mut features = extra_features.to_vec(); if builder.build.config.cargo_native_static { if path.ends_with("cargo") || path.ends_with("rls") diff --git a/src/bootstrap/toolstate.rs b/src/bootstrap/toolstate.rs index b068c8200a..31ff01d5be 100644 --- a/src/bootstrap/toolstate.rs +++ b/src/bootstrap/toolstate.rs @@ -6,7 +6,7 @@ use std::env; use std::fmt; use std::fs; use std::io::{Seek, SeekFrom}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::Command; use std::time; @@ -24,7 +24,7 @@ const OS: Option<&str> = None; type ToolstateData = HashMap, ToolState>; -#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd)] #[serde(rename_all = "kebab-case")] /// Whether a tool can be compiled, tested or neither pub enum ToolState { @@ -89,7 +89,7 @@ static STABLE_TOOLS: &[(&str, &str)] = &[ static NIGHTLY_TOOLS: &[(&str, &str)] = &[ ("miri", "src/tools/miri"), ("embedded-book", "src/doc/embedded-book"), - ("rustc-guide", "src/doc/rustc-guide"), + ("rustc-dev-guide", "src/doc/rustc-dev-guide"), ]; fn print_error(tool: &str, submodule: &str) { @@ -124,7 +124,7 @@ fn check_changed_files(toolstates: &HashMap, ToolState>) { let output = t!(String::from_utf8(output.stdout)); for (tool, submodule) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) { - let changed = output.lines().any(|l| l.starts_with("M") && l.ends_with(submodule)); + let changed = output.lines().any(|l| l.starts_with('M') && l.ends_with(submodule)); eprintln!("Verifying status of {}...", tool); if !changed { continue; @@ -143,10 +143,31 @@ pub struct ToolStateCheck; impl Step for ToolStateCheck { type Output = (); - /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler. + /// Checks tool state status. /// - /// This tool in `src/tools` will verify the validity of all our links in the - /// documentation to ensure we don't have a bunch of dead ones. + /// This is intended to be used in the `checktools.sh` script. To use + /// this, set `save-toolstates` in `config.toml` so that tool status will + /// be saved to a JSON file. Then, run `x.py test --no-fail-fast` for all + /// of the tools to populate the JSON file. After that is done, this + /// command can be run to check for any status failures, and exits with an + /// error if there are any. + /// + /// This also handles publishing the results to the `history` directory of + /// the toolstate repo https://github.com/rust-lang-nursery/rust-toolstate + /// if the env var `TOOLSTATE_PUBLISH` is set. Note that there is a + /// *separate* step of updating the `latest.json` file and creating GitHub + /// issues and comments in `src/ci/publish_toolstate.sh`, which is only + /// performed on master. (The shell/python code is intended to be migrated + /// here eventually.) + /// + /// The rules for failure are: + /// * If the PR modifies a tool, the status must be test-pass. + /// NOTE: There is intent to change this, see + /// https://github.com/rust-lang/rust/issues/65000. + /// * All "stable" tools must be test-pass on the stable or beta branches. + /// * During beta promotion week, a PR is not allowed to "regress" a + /// stable tool. That is, the status is not allowed to get worse + /// (test-pass to test-fail or build-fail). fn run(self, builder: &Builder<'_>) { if builder.config.dry_run { return; @@ -171,6 +192,8 @@ impl Step for ToolStateCheck { } check_changed_files(&toolstates); + checkout_toolstate_repo(); + let old_toolstate = read_old_toolstate(); for (tool, _) in STABLE_TOOLS.iter() { let state = toolstates[*tool]; @@ -180,11 +203,24 @@ impl Step for ToolStateCheck { did_error = true; eprintln!("error: Tool `{}` should be test-pass but is {}", tool, state); } else if in_beta_week { - did_error = true; - eprintln!( - "error: Tool `{}` should be test-pass but is {} during beta week.", - tool, state - ); + let old_state = old_toolstate + .iter() + .find(|ts| ts.tool == *tool) + .expect("latest.json missing tool") + .state(); + if state < old_state { + did_error = true; + eprintln!( + "error: Tool `{}` has regressed from {} to {} during beta week.", + tool, old_state, state + ); + } else { + eprintln!( + "warning: Tool `{}` is not test-pass (is `{}`), \ + this should be fixed before beta is branched.", + tool, state + ); + } } } } @@ -247,6 +283,70 @@ impl Builder<'_> { } } +fn toolstate_repo() -> String { + env::var("TOOLSTATE_REPO") + .unwrap_or_else(|_| "https://github.com/rust-lang-nursery/rust-toolstate.git".to_string()) +} + +/// Directory where the toolstate repo is checked out. +const TOOLSTATE_DIR: &str = "rust-toolstate"; + +/// Checks out the toolstate repo into `TOOLSTATE_DIR`. +fn checkout_toolstate_repo() { + if let Ok(token) = env::var("TOOLSTATE_REPO_ACCESS_TOKEN") { + prepare_toolstate_config(&token); + } + if Path::new(TOOLSTATE_DIR).exists() { + eprintln!("Cleaning old toolstate directory..."); + t!(fs::remove_dir_all(TOOLSTATE_DIR)); + } + + let status = Command::new("git") + .arg("clone") + .arg("--depth=1") + .arg(toolstate_repo()) + .arg(TOOLSTATE_DIR) + .status(); + let success = match status { + Ok(s) => s.success(), + Err(_) => false, + }; + if !success { + panic!("git clone unsuccessful (status: {:?})", status); + } +} + +/// Sets up config and authentication for modifying the toolstate repo. +fn prepare_toolstate_config(token: &str) { + fn git_config(key: &str, value: &str) { + let status = Command::new("git").arg("config").arg("--global").arg(key).arg(value).status(); + let success = match status { + Ok(s) => s.success(), + Err(_) => false, + }; + if !success { + panic!("git config key={} value={} successful (status: {:?})", key, value, status); + } + } + + // If changing anything here, then please check that src/ci/publish_toolstate.sh is up to date + // as well. + git_config("user.email", "7378925+rust-toolstate-update@users.noreply.github.com"); + git_config("user.name", "Rust Toolstate Update"); + git_config("credential.helper", "store"); + + let credential = format!("https://{}:x-oauth-basic@github.com\n", token,); + let git_credential_path = PathBuf::from(t!(env::var("HOME"))).join(".git-credentials"); + t!(fs::write(&git_credential_path, credential)); +} + +/// Reads the latest toolstate from the toolstate repo. +fn read_old_toolstate() -> Vec { + let latest_path = Path::new(TOOLSTATE_DIR).join("_data").join("latest.json"); + let old_toolstate = t!(fs::read(latest_path)); + t!(serde_json::from_slice(&old_toolstate)) +} + /// This function `commit_toolstate_change` provides functionality for pushing a change /// to the `rust-toolstate` repository. /// @@ -274,45 +374,7 @@ impl Builder<'_> { /// * See /// if a private email by GitHub is wanted. fn commit_toolstate_change(current_toolstate: &ToolstateData, in_beta_week: bool) { - fn git_config(key: &str, value: &str) { - let status = Command::new("git").arg("config").arg("--global").arg(key).arg(value).status(); - let success = match status { - Ok(s) => s.success(), - Err(_) => false, - }; - if !success { - panic!("git config key={} value={} successful (status: {:?})", key, value, status); - } - } - - // If changing anything here, then please check that src/ci/publish_toolstate.sh is up to date - // as well. - git_config("user.email", "7378925+rust-toolstate-update@users.noreply.github.com"); - git_config("user.name", "Rust Toolstate Update"); - git_config("credential.helper", "store"); - - let credential = format!( - "https://{}:x-oauth-basic@github.com\n", - t!(env::var("TOOLSTATE_REPO_ACCESS_TOKEN")), - ); - let git_credential_path = PathBuf::from(t!(env::var("HOME"))).join(".git-credentials"); - t!(fs::write(&git_credential_path, credential)); - - let status = Command::new("git") - .arg("clone") - .arg("--depth=1") - .arg(t!(env::var("TOOLSTATE_REPO"))) - .status(); - let success = match status { - Ok(s) => s.success(), - Err(_) => false, - }; - if !success { - panic!("git clone successful (status: {:?})", status); - } - - let old_toolstate = t!(fs::read("rust-toolstate/_data/latest.json")); - let old_toolstate: Vec = t!(serde_json::from_slice(&old_toolstate)); + let old_toolstate = read_old_toolstate(); let message = format!("({} CI update)", OS.expect("linux/windows only")); let mut success = false; @@ -322,7 +384,7 @@ fn commit_toolstate_change(current_toolstate: &ToolstateData, in_beta_week: bool // `git commit` failing means nothing to commit. let status = t!(Command::new("git") - .current_dir("rust-toolstate") + .current_dir(TOOLSTATE_DIR) .arg("commit") .arg("-a") .arg("-m") @@ -334,7 +396,7 @@ fn commit_toolstate_change(current_toolstate: &ToolstateData, in_beta_week: bool } let status = t!(Command::new("git") - .current_dir("rust-toolstate") + .current_dir(TOOLSTATE_DIR) .arg("push") .arg("origin") .arg("master") @@ -347,14 +409,14 @@ fn commit_toolstate_change(current_toolstate: &ToolstateData, in_beta_week: bool eprintln!("Sleeping for 3 seconds before retrying push"); std::thread::sleep(std::time::Duration::from_secs(3)); let status = t!(Command::new("git") - .current_dir("rust-toolstate") + .current_dir(TOOLSTATE_DIR) .arg("fetch") .arg("origin") .arg("master") .status()); assert!(status.success()); let status = t!(Command::new("git") - .current_dir("rust-toolstate") + .current_dir(TOOLSTATE_DIR) .arg("reset") .arg("--hard") .arg("origin/master") @@ -375,19 +437,13 @@ fn change_toolstate( let mut regressed = false; for repo_state in old_toolstate { let tool = &repo_state.tool; - let state = if cfg!(target_os = "linux") { - &repo_state.linux - } else if cfg!(windows) { - &repo_state.windows - } else { - unimplemented!() - }; + let state = repo_state.state(); let new_state = current_toolstate[tool.as_str()]; - if new_state != *state { + if new_state != state { eprintln!("The state of `{}` has changed from `{}` to `{}`", tool, state, new_state); - if (new_state as u8) < (*state as u8) { - if !["rustc-guide", "miri", "embedded-book"].contains(&tool.as_str()) { + if new_state < state { + if !NIGHTLY_TOOLS.iter().any(|(name, _path)| name == tool) { regressed = true; } } @@ -403,7 +459,9 @@ fn change_toolstate( let toolstate_serialized = t!(serde_json::to_string(¤t_toolstate)); - let history_path = format!("rust-toolstate/history/{}.tsv", OS.expect("linux/windows only")); + let history_path = Path::new(TOOLSTATE_DIR) + .join("history") + .join(format!("{}.tsv", OS.expect("linux/windows only"))); let mut file = t!(fs::read_to_string(&history_path)); let end_of_first_line = file.find('\n').unwrap(); file.insert_str(end_of_first_line, &format!("\n{}\t{}", commit.trim(), toolstate_serialized)); @@ -418,3 +476,15 @@ struct RepoState { commit: String, datetime: String, } + +impl RepoState { + fn state(&self) -> ToolState { + if cfg!(target_os = "linux") { + self.linux + } else if cfg!(windows) { + self.windows + } else { + unimplemented!() + } + } +} diff --git a/src/bootstrap/util.rs b/src/bootstrap/util.rs index 7d1efe4610..eac790fe50 100644 --- a/src/bootstrap/util.rs +++ b/src/bootstrap/util.rs @@ -98,7 +98,7 @@ impl Drop for TimeIt { fn drop(&mut self) { let time = self.1.elapsed(); if !self.0 { - println!("\tfinished in {}.{:03}", time.as_secs(), time.subsec_nanos() / 1_000_000); + println!("\tfinished in {}.{:03}", time.as_secs(), time.subsec_millis()); } } } diff --git a/src/ci/azure-pipelines/try.yml b/src/ci/azure-pipelines/try.yml index f8ddf0eb46..a29d6f9ae1 100644 --- a/src/ci/azure-pipelines/try.yml +++ b/src/ci/azure-pipelines/try.yml @@ -20,7 +20,7 @@ jobs: # The macOS and Windows builds here are currently disabled due to them not being # overly necessary on `try` builds. We also don't actually have anything that -# consumes the artifacts currently. Perhaps one day we can reenable, but for now +# consumes the artifacts currently. Perhaps one day we can re-enable, but for now # it helps free up capacity on Azure. # - job: macOS # timeoutInMinutes: 600 diff --git a/src/ci/cpu-usage-over-time.py b/src/ci/cpu-usage-over-time.py index daf21670b3..78ac060368 100644 --- a/src/ci/cpu-usage-over-time.py +++ b/src/ci/cpu-usage-over-time.py @@ -148,11 +148,11 @@ else: print('unknown platform', sys.platform) sys.exit(1) -cur_state = State(); +cur_state = State() print("Time,Idle") while True: - time.sleep(1); - next_state = State(); + time.sleep(1) + next_state = State() now = datetime.datetime.utcnow().isoformat() idle = next_state.idle_since(cur_state) print("%s,%s" % (now, idle)) diff --git a/src/ci/docker/dist-various-2/Dockerfile b/src/ci/docker/dist-various-2/Dockerfile index 2ae6c58941..5bb5436bec 100644 --- a/src/ci/docker/dist-various-2/Dockerfile +++ b/src/ci/docker/dist-various-2/Dockerfile @@ -48,7 +48,7 @@ RUN /tmp/build-solaris-toolchain.sh sparcv9 sparcv9 solaris-sparc COPY dist-various-2/build-x86_64-fortanix-unknown-sgx-toolchain.sh /tmp/ # We pass the commit id of the port of LLVM's libunwind to the build script. # Any update to the commit id here, should cause the container image to be re-built from this point on. -RUN /tmp/build-x86_64-fortanix-unknown-sgx-toolchain.sh "53b586346f2c7870e20b170decdc30729d97c42b" +RUN /tmp/build-x86_64-fortanix-unknown-sgx-toolchain.sh "5125c169b30837208a842f85f7ae44a83533bd0e" COPY dist-various-2/build-wasi-toolchain.sh /tmp/ RUN /tmp/build-wasi-toolchain.sh diff --git a/src/ci/docker/x86_64-gnu-tools/checktools.sh b/src/ci/docker/x86_64-gnu-tools/checktools.sh index e57fe22713..72325c7b94 100755 --- a/src/ci/docker/x86_64-gnu-tools/checktools.sh +++ b/src/ci/docker/x86_64-gnu-tools/checktools.sh @@ -14,7 +14,7 @@ python2.7 "$X_PY" test --no-fail-fast \ src/doc/rust-by-example \ src/doc/embedded-book \ src/doc/edition-guide \ - src/doc/rustc-guide \ + src/doc/rustc-dev-guide \ src/tools/clippy \ src/tools/rls \ src/tools/rustfmt \ diff --git a/src/ci/scripts/install-msys2-packages.sh b/src/ci/scripts/install-msys2-packages.sh index 843a2bf2d5..22b9854ad5 100755 --- a/src/ci/scripts/install-msys2-packages.sh +++ b/src/ci/scripts/install-msys2-packages.sh @@ -13,6 +13,7 @@ if isWindows; then # one way or another. The msys interpreters seem to have weird path conversions # baked in which break LLVM's build system one way or another, so let's use the # native version which keeps everything as native as possible. - cp C:/Python27amd64/python.exe C:/Python27amd64/python2.7.exe - ciCommandAddPath "C:\\Python27amd64" + python_home="C:/hostedtoolcache/windows/Python/2.7.17/x64" + cp "${python_home}/python.exe" "${python_home}/python2.7.exe" + ciCommandAddPath "C:\\hostedtoolcache\\windows\\Python\\2.7.17\\x64" fi diff --git a/src/doc/book/.cargo/config b/src/doc/book/.cargo/config new file mode 100644 index 0000000000..2de1871303 --- /dev/null +++ b/src/doc/book/.cargo/config @@ -0,0 +1,3 @@ +[cargo-new] +name = "Your Name" +email = "you@example.com" diff --git a/src/doc/book/.travis.yml b/src/doc/book/.travis.yml index d9a907c9fc..5221c0edf7 100644 --- a/src/doc/book/.travis.yml +++ b/src/doc/book/.travis.yml @@ -3,7 +3,7 @@ dist: trusty language: rust cache: cargo rust: - - 1.37.0 + - 1.41.0 branches: only: - master diff --git a/src/doc/book/2018-edition/src/ch18-02-refutability.md b/src/doc/book/2018-edition/src/ch18-02-refutability.md index 074f950e65..a3e2bcff76 100644 --- a/src/doc/book/2018-edition/src/ch18-02-refutability.md +++ b/src/doc/book/2018-edition/src/ch18-02-refutability.md @@ -7,4 +7,4 @@ version of the book](../ch18-02-refutability.html) instead. If you have an internet connection, you can [find a copy distributed with Rust -1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch18-02-refuatbility.html). \ No newline at end of file +1.30](https://doc.rust-lang.org/1.30.0/book/2018-edition/ch18-02-refutability.html). \ No newline at end of file diff --git a/src/doc/book/ADMIN_TASKS.md b/src/doc/book/ADMIN_TASKS.md new file mode 100644 index 0000000000..ad02693a33 --- /dev/null +++ b/src/doc/book/ADMIN_TASKS.md @@ -0,0 +1,109 @@ +# Administrative Tasks + +This documentation is for Carol and Steve and anyone else managing the repo to remember how to do +occasional maintenance tasks. + +## Update the `rustc` version + +- Change the version number in `.travis.yml` +- Change the version number in `rust-toolchain`, which should change the version you're using + locally with `rustup` +- Change the version number in `src/title-page.md` +- Run `./tools/update-rustc.sh` (see its commented code for details on what it does) +- Inspect the changes (by looking at the files changed according to git) and their effects (by + looking at the files in `tmp/book-before` and `tmp/book-after`) and commit them if they look good +- Grep for `manual-regeneration` and follow the instructions in those places to update output that + cannot be generated by a script + +## Release a new version of the listings + +We now make `.tar` files of complete projects containing every listing available [as GitHub +Releases](https://github.com/rust-lang/book/releases). To create a new release artifact, for +example if there have been code changes due to edits or due to updating Rust and `rustfmt`, do the +following: + +- Create a git tag for the release and push it to GitHub, or create a new tag by going to the + GitHub UI, [drafting a new release](https://github.com/rust-lang/book/releases/new), and entering + a new tag instead of selecting an existing tag +- Run `cargo run --bin release_listings`, which will generate `tmp/listings.tar.gz` +- Upload `tmp/listings.tar.gz` in the GitHub UI for the draft release +- Publish the release + +## Add a new listing + +To facilitate the scripts that run `rustfmt` on all the listings, update the output when the +compiler is updated, and produce release artifacts containing full projects for the listings, any +listing beyond the most trivial should be extracted into a file. To do that: + +- Find where the new listing should go in the `listings` directory. + - There is one subdirectory for each chapter + - Numbered listings should use `listing-[chapter num]-[listing num]` for their directory names. + - Listings without a number should start with `no-listing-` followed by a number that indicates + its position in the chapter relative to the other listings without numbers in the chapter, then + a short description that someone could read to find the code they're looking for. + - Listings used only for displaying the output of the code (for example, when we say "if we had + written x instead of y, we would get this compiler error:" but we don't actually show code x) + should be named with `output-only-` followed by a number that indicates its position in the + chapter relative to the other listings used only for output, then a short description that + authors or contributors could read to find the code they're looking for. + - **Remember to adjust surrounding listing numbers as appropriate!** +- Create a full Cargo project in that directory, either by using `cargo new` or copying another + listing as a starting point. +- Add the code and any surrounding code needed to create a full working example. +- If you only want to show part of the code in the file, use anchor comments (`// ANCHOR: some_tag` + and `// ANCHOR_END: some_tag`) to mark the parts of the file you want to show. +- For Rust code, use the `{{#rustdoc_include [fileame:some_tag]}}` directive within the code blocks + in the text. The `rustdoc_include` directive gives the code that doesn't get displayed to + `rustdoc` for `mdbook test` purposes. +- For anything else, use the `{{#include [filename:some_tag]}}` directive. +- If you want to display the output of a command in the text as well, create an `output.txt` file + in the listing's directory as follows: + - Run the command, like `cargo run` or `cargo test`, and copy all of the output. + - Create a new `output.txt` file with the first line `$ [the command you ran]`. + - Paste the output you just copied. + - Run `./tools/update-rustc.sh`, which should perform some normalization on the compiler output. + - Include the output in the text with the `{{#include [filename]}}` directive. + - Add and commit output.txt. +- If you want to display output but for some reason it can't be generated by a script (say, because + of user input or external events like making a web request), keep the output inline but make a + comment that contains `manual-regeneration` and instructions for manually updating the inline + output. +- If you don't want this example to even be attempted to be formatted by `rustfmt` (for example + because the example doesn't parse on purpose), add a `rustfmt-ignore` file in the listing's + directory and the reason it's not being formatted as the contents of that file (in case it's a + rustfmt bug that might get fixed someday). + +## See the effect of some change on the rendered book + +To check, say, updating `mdbook` or changing the way files get included: + +- Generate a built book before the change you want to test by running `mdbook build -d + tmp/book-before` +- Apply the changes you want to test and run `mdbook build -d tmp/book-after` +- Run `./tools/megadiff.sh` +- Files remaining in `tmp/book-before` and `tmp/book-after` have differences you can manually + inspect with your favorite diff viewing mechanism + +## Produce new markdown files for No Starch + +- Run `./tools/nostarch.sh` +- Spot check the files that script created in the `nostarch` directory +- Check them into git if you're starting a round of edits + +## Produce markdown from docx for diffing + +- TODO Carol to document this next time she does it + +## Generate Graphviz dot + +We're using [Graphviz](http://graphviz.org/) for some of the diagrams in the +book. The source for those files live in the `dot` directory. To turn a `dot` +file, for example, `dot/trpl04-01.dot` into an `svg`, run: + +```bash +$ dot dot/trpl04-01.dot -Tsvg > src/img/trpl04-01.svg +``` + +In the generated SVG, remove the width and the height attributes from the `svg` +element and set the `viewBox` attribute to `0.00 0.00 1000.00 1000.00` or other +values that don't cut off the image. diff --git a/src/doc/book/Cargo.lock b/src/doc/book/Cargo.lock index dbf955717c..b3469e3513 100644 --- a/src/doc/book/Cargo.lock +++ b/src/doc/book/Cargo.lock @@ -1,144 +1,275 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +[[package]] +name = "adler32" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "aho-corasick" -version = "0.5.3" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "crc32fast" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "docopt" -version = "0.6.86" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "lazy_static 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 0.1.80 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", - "strsim 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", + "strsim 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "kernel32-sys" -version = "0.2.2" +name = "filetime" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "flate2" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "miniz_oxide 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "lazy_static" -version = "0.2.10" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libc" -version = "0.2.33" +version = "0.2.66" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "memchr" -version = "0.1.11" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "miniz_oxide" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "proc-macro2" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "redox_syscall" +version = "0.1.56" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "regex" -version = "0.1.80" +version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "aho-corasick 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", - "regex-syntax 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", - "thread_local 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex-syntax 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "thread_local 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "regex-syntax" -version = "0.3.9" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "rust-book" version = "0.0.1" dependencies = [ - "docopt 0.6.86 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 0.1.80 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", - "walkdir 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "docopt 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "flate2 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", + "tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)", + "walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "serde" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "rustc-serialize" -version = "0.3.24" +name = "serde_derive" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "strsim" -version = "0.5.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "thread-id" -version = "2.0.0" +name = "syn" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tar" +version = "0.4.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "filetime 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", + "xattr 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "thread_local" -version = "0.2.7" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "utf8-ranges" -version = "0.1.3" +name = "unicode-xid" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "walkdir" -version = "0.1.8" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi" -version = "0.2.8" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] -name = "winapi-build" -version = "0.1.1" +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "winapi-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "xattr" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", +] + [metadata] -"checksum aho-corasick 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ca972c2ea5f742bfce5687b9aef75506a764f61d37f8f649047846a9686ddb66" -"checksum docopt 0.6.86 (registry+https://github.com/rust-lang/crates.io-index)" = "4a7ef30445607f6fc8720f0a0a2c7442284b629cf0d049286860fae23e71c4d9" -"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" -"checksum lazy_static 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "236eb37a62591d4a41a89b7763d7de3e06ca02d5ab2815446a8bae5d2f8c2d57" -"checksum libc 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "5ba3df4dcb460b9dfbd070d41c94c19209620c191b0340b929ce748a2bcd42d2" -"checksum memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d8b629fb514376c675b98c1421e80b151d3817ac42d7c667717d282761418d20" -"checksum regex 0.1.80 (registry+https://github.com/rust-lang/crates.io-index)" = "4fd4ace6a8cf7860714a2c2280d6c1f7e6a413486c13298bbc86fd3da019402f" -"checksum regex-syntax 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "f9ec002c35e86791825ed294b50008eea9ddfc8def4420124fbc6b08db834957" -"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" -"checksum strsim 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "67f84c44fbb2f91db7fef94554e6b2ac05909c9c0b0bc23bb98d3a1aebfe7f7c" -"checksum thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" -"checksum thread_local 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "8576dbbfcaef9641452d5cf0df9b0e7eeab7694956dd33bb61515fb8f18cfdd5" -"checksum utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a1ca13c08c41c9c3e04224ed9ff80461d97e121589ff27c753a16cb10830ae0f" -"checksum walkdir 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "c66c0b9792f0a765345452775f3adbd28dde9d33f30d13e5dcc5ae17cf6f3780" -"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" -"checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" +"checksum adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" +"checksum aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "58fb5e95d83b38284460a5fda7d6470aa0b8844d283a0b614b8535e880800d2d" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" +"checksum docopt 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7f525a586d310c87df72ebcd98009e57f1cc030c8c268305287a476beb653969" +"checksum filetime 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6bd7380b54ced79dda72ecc35cc4fbbd1da6bba54afaa37e96fd1c2a308cd469" +"checksum flate2 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6bd6d6f4752952feb71363cffc9ebac9411b75b87c6ab6058c40c8900cf43c0f" +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" +"checksum memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3197e20c7edb283f87c071ddfc7a2cca8f8e0b888c242959846a6fce03c72223" +"checksum miniz_oxide 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "6f3f74f726ae935c3f514300cc6773a0c9492abc5e972d42ba0c0ebb88757625" +"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)" = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" +"checksum regex 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b5508c1941e4e7cb19965abef075d35a9a8b5cdf0846f30b4050e9b55dc55e87" +"checksum regex-syntax 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "e734e891f5b408a29efbf8309e656876276f49ab6a6ac208600b4419bd893d90" +"checksum same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +"checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" +"checksum serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" +"checksum strsim 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" +"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)" = "b3196bfbffbba3e57481b6ea32249fbaf590396a52505a2615adbb79d9d826d3" +"checksum thread_local 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" +"checksum walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +"checksum xattr 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "244c3741f4240ef46274860397c7c74e50eb23624996930e484c16679633a54c" diff --git a/src/doc/book/Cargo.toml b/src/doc/book/Cargo.toml index 3254231c04..19b2036b18 100644 --- a/src/doc/book/Cargo.toml +++ b/src/doc/book/Cargo.toml @@ -21,6 +21,14 @@ path = "tools/src/bin/lfp.rs" name = "link2print" path = "tools/src/bin/link2print.rs" +[[bin]] +name = "release_listings" +path = "tools/src/bin/release_listings.rs" + +[[bin]] +name = "remove_hidden_lines" +path = "tools/src/bin/remove_hidden_lines.rs" + [[bin]] name = "remove_links" path = "tools/src/bin/remove_links.rs" @@ -30,8 +38,10 @@ name = "remove_markup" path = "tools/src/bin/remove_markup.rs" [dependencies] -walkdir = "0.1.5" -docopt = "0.6.82" -rustc-serialize = "0.3.19" -regex = "0.1.73" -lazy_static = "0.2.1" +walkdir = "2.3.1" +docopt = "1.1.0" +serde = "1.0" +regex = "1.3.3" +lazy_static = "1.4.0" +flate2 = "1.0.13" +tar = "0.4.26" diff --git a/src/doc/book/README.md b/src/doc/book/README.md index 7075fa40a3..08d53c8423 100644 --- a/src/doc/book/README.md +++ b/src/doc/book/README.md @@ -83,20 +83,6 @@ before we merge any in, but feel free to start! [Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations [mdbook support]: https://github.com/rust-lang-nursery/mdBook/issues/5 -## Graphviz dot - -We're using [Graphviz](http://graphviz.org/) for some of the diagrams in the -book. The source for those files live in the `dot` directory. To turn a `dot` -file, for example, `dot/trpl04-01.dot` into an `svg`, run: - -```bash -$ dot dot/trpl04-01.dot -Tsvg > src/img/trpl04-01.svg -``` - -In the generated SVG, remove the width and the height attributes from the `svg` -element and set the `viewBox` attribute to `0.00 0.00 1000.00 1000.00` or other -values that don't cut off the image. - ## Spellchecking To scan source files for spelling errors, you can use the `spellcheck.sh` diff --git a/src/doc/book/ci/dictionary.txt b/src/doc/book/ci/dictionary.txt index 98f4b89e36..f2b9c50668 100644 --- a/src/doc/book/ci/dictionary.txt +++ b/src/doc/book/ci/dictionary.txt @@ -6,6 +6,7 @@ adaptor adaptors AddAssign Addr +afdc aggregator AGraph aliasability @@ -18,6 +19,7 @@ APIs app's aren args +ArgumentV associativity async atomics @@ -126,6 +128,7 @@ doccratesio DOCTYPE doesn disambiguating +DisplayBacktrace DivAssign DraftPost DSTs @@ -247,6 +250,7 @@ libpanic librarys libreoffice libstd +libunwind lifecycle LimitTracker linter @@ -334,6 +338,7 @@ parameterize ParseIntError PartialEq PartialOrd +pbcopy PendingReview PendingReviewPost PlaceholderType diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml new file mode 100644 index 0000000000..e3091e7da8 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs new file mode 100644 index 0000000000..b822b89ff3 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs @@ -0,0 +1,31 @@ +// ANCHOR: all +// ANCHOR: io +use std::io; +// ANCHOR_END: io + +// ANCHOR: main +fn main() { + // ANCHOR_END: main + // ANCHOR: print + println!("Guess the number!"); + + println!("Please input your guess."); + // ANCHOR_END: print + + // ANCHOR: string + let mut guess = String::new(); + // ANCHOR_END: string + + // ANCHOR: read + io::stdin() + .read_line(&mut guess) + // ANCHOR_END: read + // ANCHOR: expect + .expect("Failed to read line"); + // ANCHOR_END: expect + + // ANCHOR: print_guess + println!("You guessed: {}", guess); + // ANCHOR_END: print_guess +} +// ANCHOR: all diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock new file mode 100644 index 0000000000..26af308db4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.66" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs new file mode 100644 index 0000000000..60fb2a8e5f --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-02/src/main.rs @@ -0,0 +1,15 @@ +use std::io; + +fn main() { + println!("Guess the number!"); + + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + println!("You guessed: {}", guess); +} diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs new file mode 100644 index 0000000000..d5e3df7f61 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs @@ -0,0 +1,28 @@ +// ANCHOR: all +use std::io; +// ANCHOR: ch07-04 +use rand::Rng; + +fn main() { + // ANCHOR_END: ch07-04 + println!("Guess the number!"); + + // ANCHOR: ch07-04 + let secret_number = rand::thread_rng().gen_range(1, 101); + // ANCHOR_END: ch07-04 + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + println!("You guessed: {}", guess); + // ANCHOR: ch07-04 +} +// ANCHOR_END: ch07-04 +// ANCHOR_END: all diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt new file mode 100644 index 0000000000..d3b62774b6 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/output.txt @@ -0,0 +1,21 @@ +$ cargo build + Compiling libc v0.2.51 + Compiling rand_core v0.4.0 + Compiling rand_core v0.3.1 + Compiling rand v0.5.6 + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) +error[E0308]: mismatched types + --> src/main.rs:22:21 + | +22 | match guess.cmp(&secret_number) { + | ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integer + | + = note: expected reference `&std::string::String` + found reference `&{integer}` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `guessing_game`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs new file mode 100644 index 0000000000..ac432df3d0 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs @@ -0,0 +1,32 @@ +// ANCHOR: here +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + // --snip-- + // ANCHOR_END: here + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + // ANCHOR: here + + println!("You guessed: {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs new file mode 100644 index 0000000000..e4f4f87d98 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs @@ -0,0 +1,45 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); + + loop { + println!("Please input your guess."); + + let mut guess = String::new(); + + // ANCHOR: here + // --snip-- + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + // ANCHOR: ch19 + let guess: u32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + // ANCHOR_END: ch19 + + println!("You guessed: {}", guess); + + // --snip-- + // ANCHOR_END: here + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +} diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock new file mode 100644 index 0000000000..890a658000 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs new file mode 100644 index 0000000000..0d4006e946 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs @@ -0,0 +1,35 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + loop { + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: u32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + println!("You guessed: {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +} diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml new file mode 100644 index 0000000000..e3091e7da8 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt new file mode 100644 index 0000000000..2724c145d3 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished dev [unoptimized + debuginfo] target(s) in 1.50s + Running `target/debug/guessing_game` +Hello, world! diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml new file mode 100644 index 0000000000..e3091e7da8 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt new file mode 100644 index 0000000000..56fb75b382 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt @@ -0,0 +1,12 @@ +$ cargo build + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) +warning: unused `std::result::Result` that must be used + --> src/main.rs:10:5 + | +10 | io::stdin().read_line(&mut guess); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_must_use)]` on by default + = note: this `Result` may be an `Err` variant, which should be handled + + Finished dev [unoptimized + debuginfo] target(s) in 0.59s diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs new file mode 100644 index 0000000000..aaf90bd659 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs @@ -0,0 +1,13 @@ +use std::io; + +fn main() { + println!("Guess the number!"); + + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin().read_line(&mut guess); + + println!("You guessed: {}", guess); +} diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs new file mode 100644 index 0000000000..44d8db6b88 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs @@ -0,0 +1,33 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + // ANCHOR: here + // --snip-- + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: u32 = guess.trim().parse().expect("Please type a number!"); + + println!("You guessed: {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs new file mode 100644 index 0000000000..5b42f65578 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs @@ -0,0 +1,40 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + // ANCHOR: here + // --snip-- + + println!("The secret number is: {}", secret_number); + + loop { + println!("Please input your guess."); + + // --snip-- + + // ANCHOR_END: here + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: u32 = guess.trim().parse().expect("Please type a number!"); + + println!("You guessed: {}", guess); + + // ANCHOR: here + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs new file mode 100644 index 0000000000..b32fadbb12 --- /dev/null +++ b/src/doc/book/listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs @@ -0,0 +1,38 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); + + loop { + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: u32 = guess.trim().parse().expect("Please type a number!"); + + println!("You guessed: {}", guess); + + // ANCHOR: here + // --snip-- + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs new file mode 100644 index 0000000000..b492d384f0 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-01/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let y = 6; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/output.txt new file mode 100644 index 0000000000..3eb8d102a5 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.30s + Running `target/debug/branches` +The value of number is: 5 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs new file mode 100644 index 0000000000..0b8ee95fd0 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-02/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let condition = true; + let number = if condition { 5 } else { 6 }; + + println!("The value of number is: {}", number); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs new file mode 100644 index 0000000000..651ed68c8e --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-03/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let mut number = 3; + + while number != 0 { + println!("{}!", number); + + number -= 1; + } + + println!("LIFTOFF!!!"); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/output.txt new file mode 100644 index 0000000000..35c0f804a7 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/output.txt @@ -0,0 +1,9 @@ +$ cargo run + Compiling loops v0.1.0 (file:///projects/loops) + Finished dev [unoptimized + debuginfo] target(s) in 0.32s + Running `target/debug/loops` +the value is: 10 +the value is: 20 +the value is: 30 +the value is: 40 +the value is: 50 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs new file mode 100644 index 0000000000..38fd301e64 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-04/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + let a = [10, 20, 30, 40, 50]; + let mut index = 0; + + while index < 5 { + println!("the value is: {}", a[index]); + + index += 1; + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs new file mode 100644 index 0000000000..6e3cca66ea --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/listing-03-05/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let a = [10, 20, 30, 40, 50]; + + for element in a.iter() { + println!("the value is: {}", element); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt new file mode 100644 index 0000000000..4693ca9da4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) +error[E0384]: cannot assign twice to immutable variable `x` + --> src/main.rs:4:5 + | +2 | let x = 5; + | - + | | + | first assignment to `x` + | help: make this binding mutable: `mut x` +3 | println!("The value of x is: {}", x); +4 | x = 6; + | ^^^^^ cannot assign twice to immutable variable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0384`. +error: could not compile `variables`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs new file mode 100644 index 0000000000..a6c7ac071f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let x = 5; + println!("The value of x is: {}", x); + x = 6; + println!("The value of x is: {}", x); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt new file mode 100644 index 0000000000..8ed6598ff1 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) + Finished dev [unoptimized + debuginfo] target(s) in 0.30s + Running `target/debug/variables` +The value of x is: 5 +The value of x is: 6 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs new file mode 100644 index 0000000000..c4e4a1953d --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let mut x = 5; + println!("The value of x is: {}", x); + x = 6; + println!("The value of x is: {}", x); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt new file mode 100644 index 0000000000..64ac2bf51d --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/variables` +The value of x is: 12 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs new file mode 100644 index 0000000000..d32518011e --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = 5; + + let x = x + 1; + + let x = x * 2; + + println!("The value of x is: {}", x); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs new file mode 100644 index 0000000000..42589f5489 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let spaces = " "; + let spaces = spaces.len(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock new file mode 100644 index 0000000000..2d62cbe7af --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml new file mode 100644 index 0000000000..7915d397e2 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt new file mode 100644 index 0000000000..0f4a7d13a3 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling variables v0.1.0 (file:///projects/variables) +error[E0308]: mismatched types + --> src/main.rs:3:14 + | +3 | spaces = spaces.len(); + | ^^^^^^^^^^^^ expected `&str`, found `usize` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `variables`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs new file mode 100644 index 0000000000..f52635d0b2 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let mut spaces = " "; + spaces = spaces.len(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock new file mode 100644 index 0000000000..3b40559a79 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "floating-point" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml new file mode 100644 index 0000000000..81e80c2964 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "floating-point" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs new file mode 100644 index 0000000000..6f4f0fe872 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let x = 2.0; // f64 + + let y: f32 = 3.0; // f32 +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock new file mode 100644 index 0000000000..94a12b2553 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "numeric-operations" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml new file mode 100644 index 0000000000..00601dde45 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "numeric-operations" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs new file mode 100644 index 0000000000..0a784bbc21 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs @@ -0,0 +1,16 @@ +fn main() { + // addition + let sum = 5 + 10; + + // subtraction + let difference = 95.5 - 4.3; + + // multiplication + let product = 4 * 30; + + // division + let quotient = 56.7 / 32.2; + + // remainder + let remainder = 43 % 5; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock new file mode 100644 index 0000000000..5d5728ebd9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "boolean" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml new file mode 100644 index 0000000000..783df3ddf3 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "boolean" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs new file mode 100644 index 0000000000..2c56e62f94 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let t = true; + + let f: bool = false; // with explicit type annotation +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock new file mode 100644 index 0000000000..bb58446cc7 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "char" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml new file mode 100644 index 0000000000..cfde83b8c6 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "char" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs new file mode 100644 index 0000000000..4b8d9d930b --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let c = 'z'; + let z = 'ℤ'; + let heart_eyed_cat = '😻'; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock new file mode 100644 index 0000000000..f57f0767c9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tuples" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml new file mode 100644 index 0000000000..8d6c2d577d --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tuples" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs new file mode 100644 index 0000000000..b7b51fb2f9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let tup: (i32, f64, u8) = (500, 6.4, 1); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock new file mode 100644 index 0000000000..f57f0767c9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tuples" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml new file mode 100644 index 0000000000..8d6c2d577d --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tuples" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs new file mode 100644 index 0000000000..35dcb442ea --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let tup = (500, 6.4, 1); + + let (x, y, z) = tup; + + println!("The value of y is: {}", y); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock new file mode 100644 index 0000000000..f57f0767c9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tuples" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml new file mode 100644 index 0000000000..8d6c2d577d --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tuples" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs new file mode 100644 index 0000000000..1b1e646fd6 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x: (i32, f64, u8) = (500, 6.4, 1); + + let five_hundred = x.0; + + let six_point_four = x.1; + + let one = x.2; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock new file mode 100644 index 0000000000..68e3c59678 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arrays" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml new file mode 100644 index 0000000000..ec97b7d5e7 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "arrays" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs new file mode 100644 index 0000000000..d475901ce6 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let a = [1, 2, 3, 4, 5]; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock new file mode 100644 index 0000000000..68e3c59678 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arrays" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml new file mode 100644 index 0000000000..ec97b7d5e7 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "arrays" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs new file mode 100644 index 0000000000..d33e3174f6 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let a = [1, 2, 3, 4, 5]; + + let first = a[0]; + let second = a[1]; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock new file mode 100644 index 0000000000..68e3c59678 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arrays" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml new file mode 100644 index 0000000000..ec97b7d5e7 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "arrays" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt new file mode 100644 index 0000000000..be3ef310f8 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling arrays v0.1.0 (file:///projects/arrays) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/arrays` +thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:5:19 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs new file mode 100644 index 0000000000..5ce0ed4a5b --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + let a = [1, 2, 3, 4, 5]; + let index = 10; + + let element = a[index]; + + println!("The value of element is: {}", element); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt new file mode 100644 index 0000000000..723fad32ad --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 0.28s + Running `target/debug/functions` +Hello, world! +Another function. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs new file mode 100644 index 0000000000..38be8565bf --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + println!("Hello, world!"); + + another_function(); +} + +fn another_function() { + println!("Another function."); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt new file mode 100644 index 0000000000..546bbc0473 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 1.21s + Running `target/debug/functions` +The value of x is: 5 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs new file mode 100644 index 0000000000..029446c044 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + another_function(5); +} + +fn another_function(x: i32) { + println!("The value of x is: {}", x); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt new file mode 100644 index 0000000000..d651191cd4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/functions` +The value of x is: 5 +The value of y is: 6 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs new file mode 100644 index 0000000000..fe476db0a8 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + another_function(5, 6); +} + +fn another_function(x: i32, y: i32) { + println!("The value of x is: {}", x); + println!("The value of y is: {}", y); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock new file mode 100644 index 0000000000..89a654d696 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore new file mode 100644 index 0000000000..06a976dd46 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/rustfmt-ignore @@ -0,0 +1 @@ +This listing deliberately doesn't parse so rustfmt fails. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs new file mode 100644 index 0000000000..988f9653ed --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let x = (let y = 6); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs new file mode 100644 index 0000000000..baa853e187 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + let x = 5; + + let y = { + let x = 3; + x + 1 + }; + + println!("The value of y is: {}", y); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt new file mode 100644 index 0000000000..a457e33996 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) + Finished dev [unoptimized + debuginfo] target(s) in 0.30s + Running `target/debug/functions` +The value of x is: 5 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs new file mode 100644 index 0000000000..5303b10827 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs @@ -0,0 +1,9 @@ +fn five() -> i32 { + 5 +} + +fn main() { + let x = five(); + + println!("The value of x is: {}", x); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs new file mode 100644 index 0000000000..b4c84437a9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = plus_one(5); + + println!("The value of x is: {}", x); +} + +fn plus_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock new file mode 100644 index 0000000000..88287d1363 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml new file mode 100644 index 0000000000..291680cf8f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt new file mode 100644 index 0000000000..1c80331541 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling functions v0.1.0 (file:///projects/functions) +error[E0308]: mismatched types + --> src/main.rs:7:24 + | +7 | fn plus_one(x: i32) -> i32 { + | -------- ^^^ expected `i32`, found `()` + | | + | implicitly returns `()` as its body has no tail or `return` expression +8 | x + 1; + | - help: consider removing this semicolon + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `functions`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs new file mode 100644 index 0000000000..c9c4edc190 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = plus_one(5); + + println!("The value of x is: {}", x); +} + +fn plus_one(x: i32) -> i32 { + x + 1; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock new file mode 100644 index 0000000000..a289136a62 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "comments" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml new file mode 100644 index 0000000000..c53d87571f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "comments" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs new file mode 100644 index 0000000000..535f4b993b --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let lucky_number = 7; // I’m feeling lucky today +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock new file mode 100644 index 0000000000..a289136a62 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "comments" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml new file mode 100644 index 0000000000..c53d87571f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "comments" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs new file mode 100644 index 0000000000..81cd935591 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + // I’m feeling lucky today + let lucky_number = 7; +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt new file mode 100644 index 0000000000..3d8c7dc333 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/branches` +condition was true diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs new file mode 100644 index 0000000000..e64a42adf7 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let number = 3; + + if number < 5 { + println!("condition was true"); + } else { + println!("condition was false"); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt new file mode 100644 index 0000000000..e40da961c9 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/branches` +condition was false diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs new file mode 100644 index 0000000000..f7d76cf558 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let number = 7; + // ANCHOR_END: here + + if number < 5 { + println!("condition was true"); + } else { + println!("condition was false"); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt new file mode 100644 index 0000000000..b3442affe0 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) +error[E0308]: mismatched types + --> src/main.rs:4:8 + | +4 | if number { + | ^^^^^^ expected `bool`, found integer + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `branches`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs new file mode 100644 index 0000000000..bc4af767b1 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let number = 3; + + if number { + println!("number was three"); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs new file mode 100644 index 0000000000..704650f467 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let number = 3; + + if number != 0 { + println!("number was something other than zero"); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt new file mode 100644 index 0000000000..b218941ad0 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) + Finished dev [unoptimized + debuginfo] target(s) in 0.31s + Running `target/debug/branches` +number is divisible by 3 diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs new file mode 100644 index 0000000000..d0ef9b2c15 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let number = 6; + + if number % 4 == 0 { + println!("number is divisible by 4"); + } else if number % 3 == 0 { + println!("number is divisible by 3"); + } else if number % 2 == 0 { + println!("number is divisible by 2"); + } else { + println!("number is not divisible by 4, 3, or 2"); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock new file mode 100644 index 0000000000..4ca0c2dbdb --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "branches" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml new file mode 100644 index 0000000000..8ddf691495 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "branches" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt new file mode 100644 index 0000000000..f47a2a8067 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling branches v0.1.0 (file:///projects/branches) +error[E0308]: if and else have incompatible types + --> src/main.rs:4:44 + | +4 | let number = if condition { 5 } else { "six" }; + | - ^^^^^ expected integer, found `&str` + | | + | expected because of this + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `branches`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs new file mode 100644 index 0000000000..440b286f5e --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let condition = true; + + let number = if condition { 5 } else { "six" }; + + println!("The value of number is: {}", number); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs new file mode 100644 index 0000000000..f1692e4625 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + loop { + println!("again!"); + } +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs new file mode 100644 index 0000000000..6ffdab5a4b --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let mut counter = 0; + + let result = loop { + counter += 1; + + if counter == 10 { + break counter * 2; + } + }; + + println!("The result is {}", result); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock new file mode 100644 index 0000000000..9942b362ac --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "loops" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml new file mode 100644 index 0000000000..b5ed848ab4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "loops" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs new file mode 100644 index 0000000000..e7286a84e4 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + for number in (1..4).rev() { + println!("{}!", number); + } + println!("LIFTOFF!!!"); +} diff --git a/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock new file mode 100644 index 0000000000..b5664bc336 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "no_type_annotations" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml new file mode 100644 index 0000000000..964f9e8e23 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "no_type_annotations" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt new file mode 100644 index 0000000000..5b00236206 --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt @@ -0,0 +1,14 @@ +$ cargo build + Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations) +error[E0282]: type annotations needed + --> src/main.rs:2:9 + | +2 | let guess = "42".parse().expect("Not a number!"); + | ^^^^^ consider giving `guess` a type + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0282`. +error: could not compile `no_type_annotations`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs new file mode 100644 index 0000000000..f41c55805f --- /dev/null +++ b/src/doc/book/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let guess = "42".parse().expect("Not a number!"); +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/src/main.rs new file mode 100644 index 0000000000..148ad84c97 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-01/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + { // s is not valid here, it’s not yet declared + let s = "hello"; // s is valid from this point forward + + // do stuff with s + } // this scope is now over, and s is no longer valid + // ANCHOR_END: here +} \ No newline at end of file diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/src/main.rs new file mode 100644 index 0000000000..de0f1b3251 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-02/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let x = 5; + let y = x; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/src/main.rs new file mode 100644 index 0000000000..23906b4306 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-03/src/main.rs @@ -0,0 +1,23 @@ +fn main() { + let s = String::from("hello"); // s comes into scope + + takes_ownership(s); // s's value moves into the function... + // ... and so is no longer valid here + + let x = 5; // x comes into scope + + makes_copy(x); // x would move into the function, + // but i32 is Copy, so it’s okay to still + // use x afterward + +} // Here, x goes out of scope, then s. But because s's value was moved, nothing + // special happens. + +fn takes_ownership(some_string: String) { // some_string comes into scope + println!("{}", some_string); +} // Here, some_string goes out of scope and `drop` is called. The backing + // memory is freed. + +fn makes_copy(some_integer: i32) { // some_integer comes into scope + println!("{}", some_integer); +} // Here, some_integer goes out of scope. Nothing special happens. diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/src/main.rs new file mode 100644 index 0000000000..e3e54a8181 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-04/src/main.rs @@ -0,0 +1,29 @@ +fn main() { + let s1 = gives_ownership(); // gives_ownership moves its return + // value into s1 + + let s2 = String::from("hello"); // s2 comes into scope + + let s3 = takes_and_gives_back(s2); // s2 is moved into + // takes_and_gives_back, which also + // moves its return value into s3 +} // Here, s3 goes out of scope and is dropped. s2 goes out of scope but was + // moved, so nothing happens. s1 goes out of scope and is dropped. + +fn gives_ownership() -> String { // gives_ownership will move its + // return value into the function + // that calls it + + let some_string = String::from("hello"); // some_string comes into scope + + some_string // some_string is returned and + // moves out to the calling + // function +} + +// takes_and_gives_back will take a String and return one +fn takes_and_gives_back(a_string: String) -> String { // a_string comes into + // scope + + a_string // a_string is returned and moves out to the calling function +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/src/main.rs new file mode 100644 index 0000000000..22aee1419e --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-05/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let s1 = String::from("hello"); + + let (s2, len) = calculate_length(s1); + + println!("The length of '{}' is {}.", s2, len); +} + +fn calculate_length(s: String) -> (String, usize) { + let length = s.len(); // len() returns the length of a String + + (s, length) +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/output.txt b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/output.txt new file mode 100644 index 0000000000..98f438f614 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference + --> src/main.rs:8:5 + | +7 | fn change(some_string: &String) { + | ------- help: consider changing this to be a mutable reference: `&mut std::string::String` +8 | some_string.push_str(", world"); + | ^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/src/main.rs new file mode 100644 index 0000000000..330ffa68ab --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-06/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let s = String::from("hello"); + + change(&s); +} + +fn change(some_string: &String) { + some_string.push_str(", world"); +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml new file mode 100644 index 0000000000..dddcb5a141 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Carol (Nichols || Goulding) "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/src/main.rs new file mode 100644 index 0000000000..3bb3c8580d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-07/src/main.rs @@ -0,0 +1,21 @@ +// ANCHOR: here +fn first_word(s: &String) -> usize { + // ANCHOR: as_bytes + let bytes = s.as_bytes(); + // ANCHOR_END: as_bytes + + // ANCHOR: iter + for (i, &item) in bytes.iter().enumerate() { + // ANCHOR_END: iter + // ANCHOR: inside_for + if item == b' ' { + return i; + } + } + + s.len() + // ANCHOR_END: inside_for +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs new file mode 100644 index 0000000000..b6182fe2b7 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs @@ -0,0 +1,24 @@ +fn first_word(s: &String) -> usize { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return i; + } + } + + s.len() +} + +// ANCHOR: here +fn main() { + let mut s = String::from("hello world"); + + let word = first_word(&s); // word will get the value 5 + + s.clear(); // this empties the String, making it equal to "" + + // word still has the value 5 here, but there's no more string that + // we could meaningfully use the value 5 with. word is now totally invalid! +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/src/main.rs new file mode 100644 index 0000000000..19a9cc74b6 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-09/src/main.rs @@ -0,0 +1,31 @@ +// ANCHOR: here +fn first_word(s: &str) -> &str { + // ANCHOR_END: here + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[..] +} + +// ANCHOR: usage +fn main() { + let my_string = String::from("hello world"); + + // first_word works on slices of `String`s + let word = first_word(&my_string[..]); + + let my_string_literal = "hello world"; + + // first_word works on slices of string literals + let word = first_word(&my_string_literal[..]); + + // Because string literals *are* string slices already, + // this works too, without the slice syntax! + let word = first_word(my_string_literal); +} +// ANCHOR_END: usage diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs new file mode 100644 index 0000000000..b68f0f1e78 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + s.push_str(", world!"); // push_str() appends a literal to a String + + println!("{}", s); // This will print `hello, world!` + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs new file mode 100644 index 0000000000..7e6d46f836 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + { + let s = String::from("hello"); // s is valid from this point forward + + // do stuff with s + } // this scope is now over, and s is no + // longer valid + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs new file mode 100644 index 0000000000..a5817e714b --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let s2 = s1; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt new file mode 100644 index 0000000000..910332ac13 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0382]: borrow of moved value: `s1` + --> src/main.rs:5:28 + | +2 | let s1 = String::from("hello"); + | -- move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait +3 | let s2 = s1; + | -- value moved here +4 | +5 | println!("{}, world!", s1); + | ^^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs new file mode 100644 index 0000000000..d0b9f18795 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let s2 = s1; + + println!("{}, world!", s1); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs new file mode 100644 index 0000000000..4e61cc1a16 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let s2 = s1.clone(); + + println!("s1 = {}, s2 = {}", s1, s2); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs new file mode 100644 index 0000000000..63a1fae248 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let x = 5; + let y = x; + + println!("x = {}, y = {}", x, y); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs new file mode 100644 index 0000000000..fd32a5fc95 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs @@ -0,0 +1,15 @@ +// ANCHOR: all +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + + let len = calculate_length(&s1); + // ANCHOR_END: here + + println!("The length of '{}' is {}.", s1, len); +} + +fn calculate_length(s: &String) -> usize { + s.len() +} +// ANCHOR_END: all diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs new file mode 100644 index 0000000000..6e40b8c300 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + let s1 = String::from("hello"); + + let len = calculate_length(&s1); + + println!("The length of '{}' is {}.", s1, len); +} + +// ANCHOR: here +fn calculate_length(s: &String) -> usize { // s is a reference to a String + s.len() +} // Here, s goes out of scope. But because it does not have ownership of what + // it refers to, nothing happens. +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs new file mode 100644 index 0000000000..fdf7f0a6f4 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let mut s = String::from("hello"); + + change(&mut s); +} + +fn change(some_string: &mut String) { + some_string.push_str(", world"); +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt new file mode 100644 index 0000000000..cb69a714b3 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0499]: cannot borrow `s` as mutable more than once at a time + --> src/main.rs:5:14 + | +4 | let r1 = &mut s; + | ------ first mutable borrow occurs here +5 | let r2 = &mut s; + | ^^^^^^ second mutable borrow occurs here +6 | +7 | println!("{}, {}", r1, r2); + | -- first borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs new file mode 100644 index 0000000000..ddbf8120f9 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + let r1 = &mut s; + let r2 = &mut s; + + println!("{}, {}", r1, r2); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs new file mode 100644 index 0000000000..4b1a5a383d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + { + let r1 = &mut s; + } // r1 goes out of scope here, so we can make a new reference with no problems. + + let r2 = &mut s; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt new file mode 100644 index 0000000000..cd4168f8ce --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable + --> src/main.rs:6:14 + | +4 | let r1 = &s; // no problem + | -- immutable borrow occurs here +5 | let r2 = &s; // no problem +6 | let r3 = &mut s; // BIG PROBLEM + | ^^^^^^ mutable borrow occurs here +7 | +8 | println!("{}, {}, and {}", r1, r2, r3); + | -- immutable borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0502`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs new file mode 100644 index 0000000000..0da04c010e --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + let r1 = &s; // no problem + let r2 = &s; // no problem + let r3 = &mut s; // BIG PROBLEM + + println!("{}, {}, and {}", r1, r2, r3); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs new file mode 100644 index 0000000000..3b0a7da659 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("hello"); + + let r1 = &s; // no problem + let r2 = &s; // no problem + println!("{} and {}", r1, r2); + // r1 and r2 are no longer used after this point + + let r3 = &mut s; // no problem + println!("{}", r3); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt new file mode 100644 index 0000000000..6381d2a305 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0106]: missing lifetime specifier + --> src/main.rs:5:16 + | +5 | fn dangle() -> &String { + | ^ help: consider giving it a 'static lifetime: `&'static` + | + = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs new file mode 100644 index 0000000000..b102697812 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let reference_to_nothing = dangle(); +} + +fn dangle() -> &String { + let s = String::from("hello"); + + &s +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock new file mode 100644 index 0000000000..9e4e62ddf5 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs new file mode 100644 index 0000000000..9fbb372a05 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let reference_to_nothing = dangle(); +} + +// ANCHOR: here +fn dangle() -> &String { // dangle returns a reference to a String + + let s = String::from("hello"); // s is a new String + + &s // we return a reference to the String, s +} // Here, s goes out of scope, and is dropped. Its memory goes away. + // Danger! +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs new file mode 100644 index 0000000000..9c20a3b2d6 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let string = no_dangle(); +} + +// ANCHOR: here +fn no_dangle() -> String { + let s = String::from("hello"); + + s +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs new file mode 100644 index 0000000000..44163af990 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let s = String::from("hello world"); + + let hello = &s[0..5]; + let world = &s[6..11]; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs new file mode 100644 index 0000000000..f44a970daa --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs @@ -0,0 +1,15 @@ +// ANCHOR: here +fn first_word(s: &String) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[..] +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt new file mode 100644 index 0000000000..0e95bb8cd6 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling ownership v0.1.0 (file:///projects/ownership) +error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable + --> src/main.rs:18:5 + | +16 | let word = first_word(&s); + | -- immutable borrow occurs here +17 | +18 | s.clear(); // error! + | ^^^^^^^^^ mutable borrow occurs here +19 | +20 | println!("the first word is: {}", word); + | ---- immutable borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0502`. +error: could not compile `ownership`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs new file mode 100644 index 0000000000..99e04018d2 --- /dev/null +++ b/src/doc/book/listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs @@ -0,0 +1,23 @@ +fn first_word(s: &String) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[..] +} + +// ANCHOR: here +fn main() { + let mut s = String::from("hello world"); + + let word = first_word(&s); + + s.clear(); // error! + + println!("the first word is: {}", word); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs new file mode 100644 index 0000000000..a7cff6ec21 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs new file mode 100644 index 0000000000..390c8ff19d --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs @@ -0,0 +1,17 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + // ANCHOR: here + let user1 = User { + email: String::from("someone@example.com"), + username: String::from("someusername123"), + active: true, + sign_in_count: 1, + }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs new file mode 100644 index 0000000000..c599c9d602 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs @@ -0,0 +1,19 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + // ANCHOR: here + let mut user1 = User { + email: String::from("someone@example.com"), + username: String::from("someusername123"), + active: true, + sign_in_count: 1, + }; + + user1.email = String::from("anotheremail@example.com"); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs new file mode 100644 index 0000000000..f934d4c000 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs @@ -0,0 +1,24 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +// ANCHOR: here +fn build_user(email: String, username: String) -> User { + User { + email: email, + username: username, + active: true, + sign_in_count: 1, + } +} +// ANCHOR_END: here + +fn main() { + let user1 = build_user( + String::from("someone@example.com"), + String::from("someusername123"), + ); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs new file mode 100644 index 0000000000..1833aa8e4d --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs @@ -0,0 +1,24 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +// ANCHOR: here +fn build_user(email: String, username: String) -> User { + User { + email, + username, + active: true, + sign_in_count: 1, + } +} +// ANCHOR_END: here + +fn main() { + let user1 = build_user( + String::from("someone@example.com"), + String::from("someusername123"), + ); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs new file mode 100644 index 0000000000..6c6d83d9be --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs @@ -0,0 +1,24 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + let user1 = User { + email: String::from("someone@example.com"), + username: String::from("someusername123"), + active: true, + sign_in_count: 1, + }; + + // ANCHOR: here + let user2 = User { + email: String::from("another@example.com"), + username: String::from("anotherusername567"), + active: user1.active, + sign_in_count: user1.sign_in_count, + }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs new file mode 100644 index 0000000000..17cef457bd --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs @@ -0,0 +1,23 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { + let user1 = User { + email: String::from("someone@example.com"), + username: String::from("someusername123"), + active: true, + sign_in_count: 1, + }; + + // ANCHOR: here + let user2 = User { + email: String::from("another@example.com"), + username: String::from("anotherusername567"), + ..user1 + }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt new file mode 100644 index 0000000000..88e10d320a --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) + Finished dev [unoptimized + debuginfo] target(s) in 0.42s + Running `target/debug/structs` +The area of the rectangle is 1500 square pixels. diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs new file mode 100644 index 0000000000..f324529fdc --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: all +fn main() { + let width1 = 30; + let height1 = 50; + + println!( + "The area of the rectangle is {} square pixels.", + area(width1, height1) + ); +} + +// ANCHOR: here +fn area(width: u32, height: u32) -> u32 { + // ANCHOR_END: here + width * height +} +// ANCHOR_END: all diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs new file mode 100644 index 0000000000..d4b77ba7ad --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + let rect1 = (30, 50); + + println!( + "The area of the rectangle is {} square pixels.", + area(rect1) + ); +} + +fn area(dimensions: (u32, u32)) -> u32 { + dimensions.0 * dimensions.1 +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs new file mode 100644 index 0000000000..62ef9acd82 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs @@ -0,0 +1,20 @@ +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!( + "The area of the rectangle is {} square pixels.", + area(&rect1) + ); +} + +fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt new file mode 100644 index 0000000000..1e03d06259 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) +error[E0277]: `Rectangle` doesn't implement `std::fmt::Display` + --> src/main.rs:12:29 + | +12 | println!("rect1 is {}", rect1); + | ^^^^^ `Rectangle` cannot be formatted with the default formatter + | + = help: the trait `std::fmt::Display` is not implemented for `Rectangle` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead + = note: required by `std::fmt::Display::fmt` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `structs`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs new file mode 100644 index 0000000000..0ff8dcc8cc --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs @@ -0,0 +1,13 @@ +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {}", rect1); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt new file mode 100644 index 0000000000..3abfb42574 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/structs` +rect1 is Rectangle { width: 30, height: 50 } diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs new file mode 100644 index 0000000000..2ffc4b8e7b --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs @@ -0,0 +1,14 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {:?}", rect1); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs new file mode 100644 index 0000000000..e4f45e868c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs @@ -0,0 +1,23 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn area(&self) -> u32 { + self.width * self.height + } +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!( + "The area of the rectangle is {} square pixels.", + rect1.area() + ); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs new file mode 100644 index 0000000000..843dab4815 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + let rect2 = Rectangle { + width: 10, + height: 40, + }; + let rect3 = Rectangle { + width: 60, + height: 45, + }; + + println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); + println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs new file mode 100644 index 0000000000..e6a32723f1 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs @@ -0,0 +1,35 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +// ANCHOR: here +impl Rectangle { + fn area(&self) -> u32 { + self.width * self.height + } + + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} +// ANCHOR_END: here + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + let rect2 = Rectangle { + width: 10, + height: 40, + }; + let rect3 = Rectangle { + width: 60, + height: 45, + }; + + println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); + println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs new file mode 100644 index 0000000000..a5d3f772a8 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs @@ -0,0 +1,37 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +// ANCHOR: here +impl Rectangle { + fn area(&self) -> u32 { + self.width * self.height + } +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} +// ANCHOR_END: here + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + let rect2 = Rectangle { + width: 10, + height: 40, + }; + let rect3 = Rectangle { + width: 60, + height: 45, + }; + + println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); + println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs new file mode 100644 index 0000000000..4c92c5d778 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + struct Color(i32, i32, i32); + struct Point(i32, i32, i32); + + let black = Color(0, 0, 0); + let origin = Point(0, 0, 0); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml new file mode 100644 index 0000000000..dec1c4bd58 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt new file mode 100644 index 0000000000..9a75534c3b --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) +error[E0106]: missing lifetime specifier + --> src/main.rs:2:15 + | +2 | username: &str, + | ^ expected lifetime parameter + +error[E0106]: missing lifetime specifier + --> src/main.rs:3:12 + | +3 | email: &str, + | ^ expected lifetime parameter + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `structs`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs new file mode 100644 index 0000000000..3cf6ffa4fc --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-02-reference-in-struct/src/main.rs @@ -0,0 +1,15 @@ +struct User { + username: &str, + email: &str, + sign_in_count: u64, + active: bool, +} + +fn main() { + let user1 = User { + email: "someone@example.com", + username: "someusername123", + active: true, + sign_in_count: 1, + }; +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs new file mode 100644 index 0000000000..d5b1692a4f --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs @@ -0,0 +1,20 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +// ANCHOR: here +impl Rectangle { + fn square(size: u32) -> Rectangle { + Rectangle { + width: size, + height: size, + } + } +} +// ANCHOR_END: here + +fn main() { + let sq = Rectangle::square(3); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt new file mode 100644 index 0000000000..c891d9342b --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) +error[E0277]: `Rectangle` doesn't implement `std::fmt::Debug` + --> src/main.rs:12:31 + | +12 | println!("rect1 is {:?}", rect1); + | ^^^^^ `Rectangle` cannot be formatted using `{:?}` + | + = help: the trait `std::fmt::Debug` is not implemented for `Rectangle` + = note: add `#[derive(Debug)]` or manually implement `std::fmt::Debug` + = note: required by `std::fmt::Debug::fmt` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `structs`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs new file mode 100644 index 0000000000..019a357ab9 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/src/main.rs @@ -0,0 +1,13 @@ +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {:?}", rect1); +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock new file mode 100644 index 0000000000..bede081a0c --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml new file mode 100644 index 0000000000..431e5c3051 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt new file mode 100644 index 0000000000..099ef9eac4 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt @@ -0,0 +1,8 @@ +$ cargo run + Compiling structs v0.1.0 (file:///projects/structs) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/structs` +rect1 is Rectangle { + width: 30, + height: 50, +} diff --git a/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs new file mode 100644 index 0000000000..84e32aee49 --- /dev/null +++ b/src/doc/book/listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/src/main.rs @@ -0,0 +1,14 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + + println!("rect1 is {:#?}", rect1); +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs new file mode 100644 index 0000000000..5b688e0f21 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs @@ -0,0 +1,23 @@ +fn main() { + // ANCHOR: here + enum IpAddrKind { + V4, + V6, + } + + struct IpAddr { + kind: IpAddrKind, + address: String, + } + + let home = IpAddr { + kind: IpAddrKind::V4, + address: String::from("127.0.0.1"), + }; + + let loopback = IpAddr { + kind: IpAddrKind::V6, + address: String::from("::1"), + }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs new file mode 100644 index 0000000000..3ba749788a --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs new file mode 100644 index 0000000000..93dce48cb4 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +enum Coin { + Penny, + Nickel, + Dime, + Quarter, +} + +fn value_in_cents(coin: Coin) -> u8 { + match coin { + Coin::Penny => 1, + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter => 25, + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs new file mode 100644 index 0000000000..3ba384fbaa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +#[derive(Debug)] // so we can inspect the state in a minute +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs new file mode 100644 index 0000000000..c86190aa7f --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs @@ -0,0 +1,18 @@ +fn main() { + // ANCHOR: here + fn plus_one(x: Option) -> Option { + match x { + // ANCHOR: first_arm + None => None, + // ANCHOR_END: first_arm + // ANCHOR: second_arm + Some(i) => Some(i + 1), + // ANCHOR_END: second_arm + } + } + + let five = Some(5); + let six = plus_one(five); + let none = plus_one(None); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs new file mode 100644 index 0000000000..222d54552c --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let some_u8_value = Some(0u8); + match some_u8_value { + Some(3) => println!("three"), + _ => (), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs new file mode 100644 index 0000000000..c631e56baf --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs @@ -0,0 +1,22 @@ +// ANCHOR: def +enum IpAddrKind { + V4, + V6, +} +// ANCHOR_END: def + +fn main() { + // ANCHOR: instance + let four = IpAddrKind::V4; + let six = IpAddrKind::V6; + // ANCHOR_END: instance + + // ANCHOR: fn_call + route(IpAddrKind::V4); + route(IpAddrKind::V6); + // ANCHOR_END: fn_call +} + +// ANCHOR: fn +fn route(ip_kind: IpAddrKind) {} +// ANCHOR_END: fn diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs new file mode 100644 index 0000000000..7d59b811ff --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + enum IpAddr { + V4(String), + V6(String), + } + + let home = IpAddr::V4(String::from("127.0.0.1")); + + let loopback = IpAddr::V6(String::from("::1")); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs new file mode 100644 index 0000000000..844a14041c --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + enum IpAddr { + V4(u8, u8, u8, u8), + V6(String), + } + + let home = IpAddr::V4(127, 0, 0, 1); + + let loopback = IpAddr::V6(String::from("::1")); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs new file mode 100644 index 0000000000..df451be8b6 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +struct QuitMessage; // unit struct +struct MoveMessage { + x: i32, + y: i32, +} +struct WriteMessage(String); // tuple struct +struct ChangeColorMessage(i32, i32, i32); // tuple struct + // ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs new file mode 100644 index 0000000000..66e0b6da11 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), + } + + // ANCHOR: here + impl Message { + fn call(&self) { + // method body would be defined here + } + } + + let m = Message::Write(String::from("hello")); + m.call(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs new file mode 100644 index 0000000000..9de5791b41 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let some_number = Some(5); + let some_string = Some("a string"); + + let absent_number: Option = None; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt new file mode 100644 index 0000000000..d3092d9fb3 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling enums v0.1.0 (file:///projects/enums) +error[E0277]: cannot add `std::option::Option` to `i8` + --> src/main.rs:5:17 + | +5 | let sum = x + y; + | ^ no implementation for `i8 + std::option::Option` + | + = help: the trait `std::ops::Add>` is not implemented for `i8` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `enums`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs new file mode 100644 index 0000000000..ec65565d42 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let x: i8 = 5; + let y: Option = Some(5); + + let sum = x + y; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs new file mode 100644 index 0000000000..3f909dcaf7 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs @@ -0,0 +1,22 @@ +enum Coin { + Penny, + Nickel, + Dime, + Quarter, +} + +// ANCHOR: here +fn value_in_cents(coin: Coin) -> u8 { + match coin { + Coin::Penny => { + println!("Lucky penny!"); + 1 + } + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter => 25, + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs new file mode 100644 index 0000000000..a4d500c11c --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs @@ -0,0 +1,31 @@ +#[derive(Debug)] +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +// ANCHOR: here +fn value_in_cents(coin: Coin) -> u8 { + match coin { + Coin::Penny => 1, + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter(state) => { + println!("State quarter from {:?}!", state); + 25 + } + } +} +// ANCHOR_END: here + +fn main() { + value_in_cents(Coin::Quarter(UsState::Alaska)); +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt new file mode 100644 index 0000000000..da9e9d9bfe --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling enums v0.1.0 (file:///projects/enums) +error[E0004]: non-exhaustive patterns: `None` not covered + --> src/main.rs:3:15 + | +3 | match x { + | ^ pattern `None` not covered + | + = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0004`. +error: could not compile `enums`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs new file mode 100644 index 0000000000..f1963d0c9d --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + fn plus_one(x: Option) -> Option { + match x { + Some(i) => Some(i + 1), + } + } + // ANCHOR_END: here + + let five = Some(5); + let six = plus_one(five); + let none = plus_one(None); +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs new file mode 100644 index 0000000000..6fc8ab058b --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + let some_u8_value = 0u8; + match some_u8_value { + 1 => println!("one"), + 3 => println!("three"), + 5 => println!("five"), + 7 => println!("seven"), + _ => (), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs new file mode 100644 index 0000000000..fb6578cf64 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + let some_u8_value = Some(0u8); + // ANCHOR: here + if let Some(3) = some_u8_value { + println!("three"); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs new file mode 100644 index 0000000000..12c4c0fec1 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs @@ -0,0 +1,24 @@ +#[derive(Debug)] +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +fn main() { + let coin = Coin::Penny; + // ANCHOR: here + let mut count = 0; + match coin { + Coin::Quarter(state) => println!("State quarter from {:?}!", state), + _ => count += 1, + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock new file mode 100644 index 0000000000..f62e8ac453 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml new file mode 100644 index 0000000000..04988d1ffa --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs new file mode 100644 index 0000000000..ba7eda27b4 --- /dev/null +++ b/src/doc/book/listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs @@ -0,0 +1,25 @@ +#[derive(Debug)] +enum UsState { + Alabama, + Alaska, + // --snip-- +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +fn main() { + let coin = Coin::Penny; + // ANCHOR: here + let mut count = 0; + if let Coin::Quarter(state) = coin { + println!("State quarter from {:?}!", state); + } else { + count += 1; + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs new file mode 100644 index 0000000000..0e40be70d9 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +mod front_of_house { + mod hosting { + fn add_to_waitlist() {} + + fn seat_at_table() {} + } + + mod serving { + fn take_order() {} + + fn serve_order() {} + + fn take_payment() {} + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/output.txt b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/output.txt new file mode 100644 index 0000000000..2a494c29ea --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/output.txt @@ -0,0 +1,20 @@ +$ cargo build + Compiling restaurant v0.1.0 (file:///projects/restaurant) +error[E0603]: module `hosting` is private + --> src/lib.rs:9:28 + | +9 | crate::front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^ + +error[E0603]: module `hosting` is private + --> src/lib.rs:12:21 + | +12 | front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0603`. +error: could not compile `restaurant`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs new file mode 100644 index 0000000000..0b8a43c6b3 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs @@ -0,0 +1,13 @@ +mod front_of_house { + mod hosting { + fn add_to_waitlist() {} + } +} + +pub fn eat_at_restaurant() { + // Absolute path + crate::front_of_house::hosting::add_to_waitlist(); + + // Relative path + front_of_house::hosting::add_to_waitlist(); +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/output.txt b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/output.txt new file mode 100644 index 0000000000..664c6a4800 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/output.txt @@ -0,0 +1,20 @@ +$ cargo build + Compiling restaurant v0.1.0 (file:///projects/restaurant) +error[E0603]: function `add_to_waitlist` is private + --> src/lib.rs:9:37 + | +9 | crate::front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^^^^^^^^^ + +error[E0603]: function `add_to_waitlist` is private + --> src/lib.rs:12:30 + | +12 | front_of_house::hosting::add_to_waitlist(); + | ^^^^^^^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0603`. +error: could not compile `restaurant`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs new file mode 100644 index 0000000000..05372dbe5e --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs @@ -0,0 +1,13 @@ +mod front_of_house { + pub mod hosting { + fn add_to_waitlist() {} + } +} + +pub fn eat_at_restaurant() { + // Absolute path + crate::front_of_house::hosting::add_to_waitlist(); + + // Relative path + front_of_house::hosting::add_to_waitlist(); +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs new file mode 100644 index 0000000000..5a6edf9832 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +pub fn eat_at_restaurant() { + // Absolute path + crate::front_of_house::hosting::add_to_waitlist(); + + // Relative path + front_of_house::hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs new file mode 100644 index 0000000000..a789379ae2 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +fn serve_order() {} + +mod back_of_house { + fn fix_incorrect_order() { + cook_order(); + super::serve_order(); + } + + fn cook_order() {} +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs new file mode 100644 index 0000000000..92c4695d50 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs @@ -0,0 +1,27 @@ +mod back_of_house { + pub struct Breakfast { + pub toast: String, + seasonal_fruit: String, + } + + impl Breakfast { + pub fn summer(toast: &str) -> Breakfast { + Breakfast { + toast: String::from(toast), + seasonal_fruit: String::from("peaches"), + } + } + } +} + +pub fn eat_at_restaurant() { + // Order a breakfast in the summer with Rye toast + let mut meal = back_of_house::Breakfast::summer("Rye"); + // Change our mind about what bread we'd like + meal.toast = String::from("Wheat"); + println!("I'd like {} toast please", meal.toast); + + // The next line won't compile if we uncomment it; we're not allowed + // to see or modify the seasonal fruit that comes with the meal + // meal.seasonal_fruit = String::from("blueberries"); +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs new file mode 100644 index 0000000000..908f1dfb71 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs @@ -0,0 +1,11 @@ +mod back_of_house { + pub enum Appetizer { + Soup, + Salad, + } +} + +pub fn eat_at_restaurant() { + let order1 = back_of_house::Appetizer::Soup; + let order2 = back_of_house::Appetizer::Salad; +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs new file mode 100644 index 0000000000..3a75683757 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs new file mode 100644 index 0000000000..6b0101b7d1 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +use self::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs new file mode 100644 index 0000000000..98414aac91 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +use crate::front_of_house::hosting::add_to_waitlist; + +pub fn eat_at_restaurant() { + add_to_waitlist(); + add_to_waitlist(); + add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs new file mode 100644 index 0000000000..4379e7c791 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-14/src/main.rs @@ -0,0 +1,6 @@ +use std::collections::HashMap; + +fn main() { + let mut map = HashMap::new(); + map.insert(1, 2); +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs new file mode 100644 index 0000000000..bfac3a07ac --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +use std::fmt; +use std::io; + +fn function1() -> fmt::Result { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} + +fn function2() -> io::Result<()> { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs new file mode 100644 index 0000000000..843490b4d0 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +use std::fmt::Result; +use std::io::Result as IoResult; + +fn function1() -> Result { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} + +fn function2() -> IoResult<()> { + // --snip-- + // ANCHOR_END: here + Ok(()) + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs new file mode 100644 index 0000000000..e948d7c38e --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +mod front_of_house { + pub mod hosting { + pub fn add_to_waitlist() {} + } +} + +pub use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock new file mode 100644 index 0000000000..c346748e55 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml new file mode 100644 index 0000000000..ad5ca696d5 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs new file mode 100644 index 0000000000..61a2023fff --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-18/src/main.rs @@ -0,0 +1,32 @@ +use rand::Rng; +// ANCHOR: here +// --snip-- +use std::{cmp::Ordering, io}; +// --snip-- +// ANCHOR_END: here + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: u32 = guess.trim().parse().expect("Please type a number!"); + + println!("You guessed: {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs new file mode 100644 index 0000000000..3fee46c443 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs @@ -0,0 +1,2 @@ +use std::io; +use std::io::Write; diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs new file mode 100644 index 0000000000..341f40a472 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs @@ -0,0 +1 @@ +use std::io::{self, Write}; diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs new file mode 100644 index 0000000000..6875dfdb63 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs @@ -0,0 +1,3 @@ +pub mod hosting { + pub fn add_to_waitlist() {} +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs new file mode 100644 index 0000000000..065b1b804c --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs @@ -0,0 +1,9 @@ +mod front_of_house; + +pub use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock new file mode 100644 index 0000000000..2b3d41ad67 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.51" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8a606a02debe2813760609f57a64a2ffd27d9fdf5b2f133eaca0b248dd92cdd2" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml new file mode 100644 index 0000000000..10932024b4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs new file mode 100644 index 0000000000..c25b0a52a8 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs @@ -0,0 +1,31 @@ +use rand::Rng; +// ANCHOR: here +// --snip-- +use std::cmp::Ordering; +use std::io; +// --snip-- +// ANCHOR_END: here + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + println!("You guessed: {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock new file mode 100644 index 0000000000..f25ab358f4 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "restaurant" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml new file mode 100644 index 0000000000..8bdd0a4188 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "restaurant" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs new file mode 100644 index 0000000000..d0a8154eaf --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs @@ -0,0 +1 @@ +pub mod hosting; diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs new file mode 100644 index 0000000000..d65f3afd13 --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs @@ -0,0 +1 @@ +pub fn add_to_waitlist() {} diff --git a/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs new file mode 100644 index 0000000000..065b1b804c --- /dev/null +++ b/src/doc/book/listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/lib.rs @@ -0,0 +1,9 @@ +mod front_of_house; + +pub use crate::front_of_house::hosting; + +pub fn eat_at_restaurant() { + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); + hosting::add_to_waitlist(); +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-01/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-01/src/main.rs new file mode 100644 index 0000000000..45e45581e2 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-01/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let v: Vec = Vec::new(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-02/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-02/src/main.rs new file mode 100644 index 0000000000..3b10a53e88 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-02/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let v = vec![1, 2, 3]; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-03/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-03/src/main.rs new file mode 100644 index 0000000000..147223f9ae --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-03/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let mut v = Vec::new(); + + v.push(5); + v.push(6); + v.push(7); + v.push(8); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-04/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-04/src/main.rs new file mode 100644 index 0000000000..abda2db660 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-04/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + { + let v = vec![1, 2, 3, 4]; + + // do stuff with v + } // <- v goes out of scope and is freed here + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-05/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-05/src/main.rs new file mode 100644 index 0000000000..9bfa37a4c2 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-05/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let v = vec![1, 2, 3, 4, 5]; + + let third: &i32 = &v[2]; + println!("The third element is {}", third); + + match v.get(2) { + Some(third) => println!("The third element is {}", third), + None => println!("There is no third element."), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-06/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-06/src/main.rs new file mode 100644 index 0000000000..783d9b110f --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-06/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let v = vec![1, 2, 3, 4, 5]; + + let does_not_exist = &v[100]; + let does_not_exist = v.get(100); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-07/output.txt b/src/doc/book/listings/ch08-common-collections/listing-08-07/output.txt new file mode 100644 index 0000000000..b50110bdba --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-07/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling collections v0.1.0 (file:///projects/collections) +error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable + --> src/main.rs:6:5 + | +4 | let first = &v[0]; + | - immutable borrow occurs here +5 | +6 | v.push(6); + | ^^^^^^^^^ mutable borrow occurs here +7 | +8 | println!("The first element is: {}", first); + | ----- immutable borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0502`. +error: could not compile `collections`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-07/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-07/src/main.rs new file mode 100644 index 0000000000..1b42274a6d --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-07/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let mut v = vec![1, 2, 3, 4, 5]; + + let first = &v[0]; + + v.push(6); + + println!("The first element is: {}", first); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-08/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-08/src/main.rs new file mode 100644 index 0000000000..38b97784be --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-08/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let v = vec![100, 32, 57]; + for i in &v { + println!("{}", i); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-09/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-09/src/main.rs new file mode 100644 index 0000000000..c62ba21b4f --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-09/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let mut v = vec![100, 32, 57]; + for i in &mut v { + *i += 50; + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-10/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-10/src/main.rs new file mode 100644 index 0000000000..c2198883b2 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-10/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + // ANCHOR: here + enum SpreadsheetCell { + Int(i32), + Float(f64), + Text(String), + } + + let row = vec![ + SpreadsheetCell::Int(3), + SpreadsheetCell::Text(String::from("blue")), + SpreadsheetCell::Float(10.12), + ]; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-11/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-11/src/main.rs new file mode 100644 index 0000000000..4cf4c81c26 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-11/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let mut s = String::new(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-12/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-12/src/main.rs new file mode 100644 index 0000000000..d9e5e768ab --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-12/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let data = "initial contents"; + + let s = data.to_string(); + + // the method also works on a literal directly: + let s = "initial contents".to_string(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-13/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-13/src/main.rs new file mode 100644 index 0000000000..b81e374536 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-13/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let s = String::from("initial contents"); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-14/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-14/src/main.rs new file mode 100644 index 0000000000..f701fd578b --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-14/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + // ANCHOR: here + let hello = String::from("السلام عليكم"); + let hello = String::from("Dobrý den"); + let hello = String::from("Hello"); + let hello = String::from("שָׁלוֹם"); + let hello = String::from("नमस्ते"); + let hello = String::from("こんにちは"); + let hello = String::from("안녕하세요"); + let hello = String::from("你好"); + let hello = String::from("Olá"); + // ANCHOR: russian + let hello = String::from("Здравствуйте"); + // ANCHOR_END: russian + // ANCHOR: spanish + let hello = String::from("Hola"); + // ANCHOR_END: spanish + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-15/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-15/src/main.rs new file mode 100644 index 0000000000..7dec657d92 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-15/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("foo"); + s.push_str("bar"); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-16/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-16/src/main.rs new file mode 100644 index 0000000000..8938dc143b --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-16/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let mut s1 = String::from("foo"); + let s2 = "bar"; + s1.push_str(s2); + println!("s2 is {}", s2); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-17/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-17/src/main.rs new file mode 100644 index 0000000000..0a9e8cc0a8 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-17/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let mut s = String::from("lo"); + s.push('l'); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-18/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-18/src/main.rs new file mode 100644 index 0000000000..93939a69fb --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-18/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("Hello, "); + let s2 = String::from("world!"); + let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-19/output.txt b/src/doc/book/listings/ch08-common-collections/listing-08-19/output.txt new file mode 100644 index 0000000000..c239f71896 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-19/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling collections v0.1.0 (file:///projects/collections) +error[E0277]: the type `std::string::String` cannot be indexed by `{integer}` + --> src/main.rs:3:13 + | +3 | let h = s1[0]; + | ^^^^^ `std::string::String` cannot be indexed by `{integer}` + | + = help: the trait `std::ops::Index<{integer}>` is not implemented for `std::string::String` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `collections`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-19/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-19/src/main.rs new file mode 100644 index 0000000000..fc08e9ceaa --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-19/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("hello"); + let h = s1[0]; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-20/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-20/src/main.rs new file mode 100644 index 0000000000..54c2010911 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-20/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-21/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-21/src/main.rs new file mode 100644 index 0000000000..0ebd20d4e8 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-21/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let teams = vec![String::from("Blue"), String::from("Yellow")]; + let initial_scores = vec![10, 50]; + + let mut scores: HashMap<_, _> = + teams.into_iter().zip(initial_scores.into_iter()).collect(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-22/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-22/src/main.rs new file mode 100644 index 0000000000..2b2a73f94a --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-22/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let field_name = String::from("Favorite color"); + let field_value = String::from("Blue"); + + let mut map = HashMap::new(); + map.insert(field_name, field_value); + // field_name and field_value are invalid at this point, try using them and + // see what compiler error you get! + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-23/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-23/src/main.rs new file mode 100644 index 0000000000..508e33cbbf --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-23/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + + let team_name = String::from("Blue"); + let score = scores.get(&team_name); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-24/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-24/src/main.rs new file mode 100644 index 0000000000..e8684cf2b6 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-24/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Blue"), 25); + + println!("{:?}", scores); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-25/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-25/src/main.rs new file mode 100644 index 0000000000..3ad97b57af --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-25/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + scores.insert(String::from("Blue"), 10); + + scores.entry(String::from("Yellow")).or_insert(50); + scores.entry(String::from("Blue")).or_insert(50); + + println!("{:?}", scores); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.lock b/src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.toml b/src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/listing-08-26/src/main.rs b/src/doc/book/listings/ch08-common-collections/listing-08-26/src/main.rs new file mode 100644 index 0000000000..f3f6aa166d --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/listing-08-26/src/main.rs @@ -0,0 +1,16 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let text = "hello world wonderful world"; + + let mut map = HashMap::new(); + + for word in text.split_whitespace() { + let count = map.entry(word).or_insert(0); + *count += 1; + } + + println!("{:?}", map); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock b/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml b/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs b/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs new file mode 100644 index 0000000000..4995650d19 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("tic"); + let s2 = String::from("tac"); + let s3 = String::from("toe"); + + let s = s1 + "-" + &s2 + "-" + &s3; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.lock b/src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.toml b/src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-02-format/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-02-format/src/main.rs b/src/doc/book/listings/ch08-common-collections/no-listing-02-format/src/main.rs new file mode 100644 index 0000000000..4a38e63d23 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-02-format/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let s1 = String::from("tic"); + let s2 = String::from("tac"); + let s3 = String::from("toe"); + + let s = format!("{}-{}-{}", s1, s2, s3); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock b/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml b/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs b/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs new file mode 100644 index 0000000000..2e7dc02e60 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + use std::collections::HashMap; + + let mut scores = HashMap::new(); + + scores.insert(String::from("Blue"), 10); + scores.insert(String::from("Yellow"), 50); + + for (key, value) in &scores { + println!("{}: {}", key, value); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock new file mode 100644 index 0000000000..d3daeff7dc --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml new file mode 100644 index 0000000000..b36871bec4 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt new file mode 100644 index 0000000000..e05d332339 --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling collections v0.1.0 (file:///projects/collections) + Finished dev [unoptimized + debuginfo] target(s) in 0.43s + Running `target/debug/collections` +thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/libcore/str/mod.rs:2069:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs new file mode 100644 index 0000000000..9283ff5bde --- /dev/null +++ b/src/doc/book/listings/ch08-common-collections/output-only-01-not-char-boundary/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let hello = "Здравствуйте"; + + let s = &hello[0..1]; +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.lock new file mode 100644 index 0000000000..4fe030fabf --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "panic" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.toml new file mode 100644 index 0000000000..310342cd33 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "panic" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-01/output.txt b/src/doc/book/listings/ch09-error-handling/listing-09-01/output.txt new file mode 100644 index 0000000000..36aef5049e --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-01/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling panic v0.1.0 (file:///projects/panic) + Finished dev [unoptimized + debuginfo] target(s) in 0.27s + Running `target/debug/panic` +thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2806:10 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-01/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-01/src/main.rs new file mode 100644 index 0000000000..70194abd79 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-01/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let v = vec![1, 2, 3]; + + v[99]; +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-03/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-03/src/main.rs new file mode 100644 index 0000000000..0dfd10b5e5 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-03/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt"); +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-04/output.txt b/src/doc/book/listings/ch09-error-handling/listing-09-04/output.txt new file mode 100644 index 0000000000..acc4f0c741 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-04/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling error-handling v0.1.0 (file:///projects/error-handling) + Finished dev [unoptimized + debuginfo] target(s) in 0.73s + Running `target/debug/error-handling` +thread 'main' panicked at 'Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:8:23 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-04/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-04/src/main.rs new file mode 100644 index 0000000000..070fc33809 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-04/src/main.rs @@ -0,0 +1,10 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt"); + + let f = match f { + Ok(file) => file, + Err(error) => panic!("Problem opening the file: {:?}", error), + }; +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-05/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-05/src/main.rs new file mode 100644 index 0000000000..8c4f773b9e --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-05/src/main.rs @@ -0,0 +1,19 @@ +use std::fs::File; +use std::io::ErrorKind; + +fn main() { + let f = File::open("hello.txt"); + + let f = match f { + Ok(file) => file, + Err(error) => match error.kind() { + ErrorKind::NotFound => match File::create("hello.txt") { + Ok(fc) => fc, + Err(e) => panic!("Problem creating the file: {:?}", e), + }, + other_error => { + panic!("Problem opening the file: {:?}", other_error) + } + }, + }; +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-06/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-06/src/main.rs new file mode 100644 index 0000000000..437d858f44 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-06/src/main.rs @@ -0,0 +1,25 @@ +// ANCHOR: here +use std::fs::File; +use std::io; +use std::io::Read; + +fn read_username_from_file() -> Result { + let f = File::open("hello.txt"); + + let mut f = match f { + Ok(file) => file, + Err(e) => return Err(e), + }; + + let mut s = String::new(); + + match f.read_to_string(&mut s) { + Ok(_) => Ok(s), + Err(e) => Err(e), + } +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-07/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-07/src/main.rs new file mode 100644 index 0000000000..b9f6172cb2 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-07/src/main.rs @@ -0,0 +1,16 @@ +// ANCHOR: here +use std::fs::File; +use std::io; +use std::io::Read; + +fn read_username_from_file() -> Result { + let mut f = File::open("hello.txt")?; + let mut s = String::new(); + f.read_to_string(&mut s)?; + Ok(s) +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-08/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-08/src/main.rs new file mode 100644 index 0000000000..f36e4d0219 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-08/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +use std::fs::File; +use std::io; +use std::io::Read; + +fn read_username_from_file() -> Result { + let mut s = String::new(); + + File::open("hello.txt")?.read_to_string(&mut s)?; + + Ok(s) +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-09/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-09/src/main.rs new file mode 100644 index 0000000000..4597dc2eea --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-09/src/main.rs @@ -0,0 +1,12 @@ +// ANCHOR: here +use std::fs; +use std::io; + +fn read_username_from_file() -> Result { + fs::read_to_string("hello.txt") +} +// ANCHOR_END: here + +fn main() { + let username = read_username_from_file().expect("Unable to get username"); +} diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.lock b/src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.lock new file mode 100644 index 0000000000..c346748e55 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.toml b/src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.toml new file mode 100644 index 0000000000..ad5ca696d5 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-10/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch09-error-handling/listing-09-10/src/main.rs b/src/doc/book/listings/ch09-error-handling/listing-09-10/src/main.rs new file mode 100644 index 0000000000..7448979a06 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/listing-09-10/src/main.rs @@ -0,0 +1,55 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +// ANCHOR: here +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 || value > 100 { + panic!("Guess value must be between 1 and 100, got {}.", value); + } + + Guess { value } + } + + pub fn value(&self) -> i32 { + self.value + } +} +// ANCHOR_END: here + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + loop { + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + let guess: i32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + let guess = Guess::new(guess); + + match guess.value().cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock new file mode 100644 index 0000000000..4fe030fabf --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "panic" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml new file mode 100644 index 0000000000..310342cd33 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "panic" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/output.txt b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/output.txt new file mode 100644 index 0000000000..1bc3dc729a --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling panic v0.1.0 (file:///projects/panic) + Finished dev [unoptimized + debuginfo] target(s) in 0.25s + Running `target/debug/panic` +thread 'main' panicked at 'crash and burn', src/main.rs:2:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/src/main.rs new file mode 100644 index 0000000000..32a4c243da --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-01-panic/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + panic!("crash and burn"); +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt new file mode 100644 index 0000000000..18262cbc40 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling error-handling v0.1.0 (file:///projects/error-handling) +error[E0308]: mismatched types + --> src/main.rs:4:18 + | +4 | let f: u32 = File::open("hello.txt"); + | --- ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`, found enum `std::result::Result` + | | + | expected due to this + | + = note: expected type `u32` + found enum `std::result::Result` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `error-handling`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs new file mode 100644 index 0000000000..a637f5f957 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs @@ -0,0 +1,7 @@ +use std::fs::File; + +fn main() { + // ANCHOR: here + let f: u32 = File::open("hello.txt"); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/src/main.rs new file mode 100644 index 0000000000..c6682cd233 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-03-closures/src/main.rs @@ -0,0 +1,14 @@ +use std::fs::File; +use std::io::ErrorKind; + +fn main() { + let f = File::open("hello.txt").unwrap_or_else(|error| { + if error.kind() == ErrorKind::NotFound { + File::create("hello.txt").unwrap_or_else(|error| { + panic!("Problem creating the file: {:?}", error); + }) + } else { + panic!("Problem opening the file: {:?}", error); + } + }); +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs new file mode 100644 index 0000000000..7b6b13ae76 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt").unwrap(); +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/src/main.rs new file mode 100644 index 0000000000..cab643bc5c --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-05-expect/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt").expect("Failed to open hello.txt"); +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt new file mode 100644 index 0000000000..17a8b2e476 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt @@ -0,0 +1,20 @@ +$ cargo run + Compiling error-handling v0.1.0 (file:///projects/error-handling) +error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`) + --> src/main.rs:4:13 + | +3 | / fn main() { +4 | | let f = File::open("hello.txt")?; + | | ^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()` +5 | | } + | |_- this function should return `Result` or `Option` to accept `?` + | + = help: the trait `std::ops::Try` is not implemented for `()` + = note: required by `std::ops::Try::from_error` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `error-handling`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs new file mode 100644 index 0000000000..8608dc13ff --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs @@ -0,0 +1,5 @@ +use std::fs::File; + +fn main() { + let f = File::open("hello.txt")?; +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs new file mode 100644 index 0000000000..7f16b8e995 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs @@ -0,0 +1,8 @@ +use std::error::Error; +use std::fs::File; + +fn main() -> Result<(), Box> { + let f = File::open("hello.txt")?; + + Ok(()) +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock new file mode 100644 index 0000000000..1fa96b7974 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "error-handling" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml new file mode 100644 index 0000000000..2a48daefb8 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "error-handling" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs new file mode 100644 index 0000000000..e829724c57 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + use std::net::IpAddr; + + let home: IpAddr = "127.0.0.1".parse().unwrap(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock new file mode 100644 index 0000000000..c346748e55 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.lock @@ -0,0 +1,87 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing_game" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.53" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.53 (registry+https://github.com/rust-lang/crates.io-index)" = "ec350a9417dfd244dc9a6c4a71e13895a4db6b92f0b106f07ebbc3f3bc580cee" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml new file mode 100644 index 0000000000..ad5ca696d5 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs new file mode 100644 index 0000000000..d89d719aa0 --- /dev/null +++ b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs @@ -0,0 +1,47 @@ +use rand::Rng; +use std::cmp::Ordering; +use std::io; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + + // ANCHOR: here + loop { + // --snip-- + + // ANCHOR_END: here + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); + + // ANCHOR: here + let guess: i32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + if guess < 1 || guess > 100 { + println!("The secret number will be between 1 and 100."); + continue; + } + + match guess.cmp(&secret_number) { + // --snip-- + // ANCHOR_END: here + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + // ANCHOR: here + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs new file mode 100644 index 0000000000..d2ba23b4a7 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let mut largest = number_list[0]; + + for number in number_list { + if number > largest { + largest = number; + } + } + + println!("The largest number is {}", largest); + // ANCHOR_END: here + assert_eq!(largest, 100); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs new file mode 100644 index 0000000000..9138dfcb44 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs @@ -0,0 +1,25 @@ +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let mut largest = number_list[0]; + + for number in number_list { + if number > largest { + largest = number; + } + } + + println!("The largest number is {}", largest); + + let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; + + let mut largest = number_list[0]; + + for number in number_list { + if number > largest { + largest = number; + } + } + + println!("The largest number is {}", largest); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs new file mode 100644 index 0000000000..7704ff3382 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs @@ -0,0 +1,31 @@ +// ANCHOR: here +fn largest(list: &[i32]) -> i32 { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + // ANCHOR_END: here + assert_eq!(result, 100); + // ANCHOR: here + + let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + // ANCHOR_END: here + assert_eq!(result, 6000); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs new file mode 100644 index 0000000000..6b483ec976 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs @@ -0,0 +1,43 @@ +// ANCHOR: here +fn largest_i32(list: &[i32]) -> i32 { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn largest_char(list: &[char]) -> char { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest_i32(&number_list); + println!("The largest number is {}", result); + // ANCHOR_END: here + assert_eq!(result, 100); + // ANCHOR: here + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest_char(&char_list); + println!("The largest char is {}", result); + // ANCHOR_END: here + assert_eq!(result, 'y'); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt new file mode 100644 index 0000000000..65498128db --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0369]: binary operation `>` cannot be applied to type `T` + --> src/main.rs:5:17 + | +5 | if item > largest { + | ---- ^ ------- T + | | + | T + | + = note: `T` might need a bound for `std::cmp::PartialOrd` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0369`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs new file mode 100644 index 0000000000..e731157060 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs @@ -0,0 +1,23 @@ +fn largest(list: &[T]) -> T { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest(&char_list); + println!("The largest char is {}", result); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs new file mode 100644 index 0000000000..4252593df9 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs @@ -0,0 +1,9 @@ +struct Point { + x: T, + y: T, +} + +fn main() { + let integer = Point { x: 5, y: 10 }; + let float = Point { x: 1.0, y: 4.0 }; +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt new file mode 100644 index 0000000000..4a67e1b595 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0308]: mismatched types + --> src/main.rs:7:38 + | +7 | let wont_work = Point { x: 5, y: 4.0 }; + | ^^^ expected integer, found floating-point number + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs new file mode 100644 index 0000000000..7883db1a6f --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs @@ -0,0 +1,8 @@ +struct Point { + x: T, + y: T, +} + +fn main() { + let wont_work = Point { x: 5, y: 4.0 }; +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs new file mode 100644 index 0000000000..615b78cfd7 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs @@ -0,0 +1,10 @@ +struct Point { + x: T, + y: U, +} + +fn main() { + let both_integer = Point { x: 5, y: 10 }; + let both_float = Point { x: 1.0, y: 4.0 }; + let integer_and_float = Point { x: 5, y: 4.0 }; +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs new file mode 100644 index 0000000000..288b64eac5 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs @@ -0,0 +1,16 @@ +struct Point { + x: T, + y: T, +} + +impl Point { + fn x(&self) -> &T { + &self.x + } +} + +fn main() { + let p = Point { x: 5, y: 10 }; + + println!("p.x = {}", p.x()); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs new file mode 100644 index 0000000000..4c5b01bdcd --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs @@ -0,0 +1,24 @@ +struct Point { + x: T, + y: T, +} + +impl Point { + fn x(&self) -> &T { + &self.x + } +} + +// ANCHOR: here +impl Point { + fn distance_from_origin(&self) -> f32 { + (self.x.powi(2) + self.y.powi(2)).sqrt() + } +} +// ANCHOR_END: here + +fn main() { + let p = Point { x: 5, y: 10 }; + + println!("p.x = {}", p.x()); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs new file mode 100644 index 0000000000..4a08d1a8d6 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs @@ -0,0 +1,22 @@ +struct Point { + x: T, + y: U, +} + +impl Point { + fn mixup(self, other: Point) -> Point { + Point { + x: self.x, + y: other.y, + } + } +} + +fn main() { + let p1 = Point { x: 5, y: 10.4 }; + let p2 = Point { x: "Hello", y: 'c' }; + + let p3 = p1.mixup(p2); + + println!("p3.x = {}, p3.y = {}", p3.x, p3.y); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs new file mode 100644 index 0000000000..cfaedb02f4 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs @@ -0,0 +1,3 @@ +pub trait Summary { + fn summarize(&self) -> String; +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs new file mode 100644 index 0000000000..c4c83329ef --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs @@ -0,0 +1,31 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +// ANCHOR: here +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs new file mode 100644 index 0000000000..fb59b84fb1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs @@ -0,0 +1,29 @@ +// ANCHOR: here +pub trait Summary { + fn summarize(&self) -> String { + String::from("(Read more...)") + } +} +// ANCHOR_END: here + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle {} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs new file mode 100644 index 0000000000..7aa6a3bd22 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs @@ -0,0 +1,23 @@ +fn largest(list: &[T]) -> T { + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest(&char_list); + println!("The largest char is {}", result); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs new file mode 100644 index 0000000000..669cc5fdc2 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs @@ -0,0 +1,22 @@ +use std::fmt::Display; + +struct Pair { + x: T, + y: T, +} + +impl Pair { + fn new(x: T, y: T) -> Self { + Self { x, y } + } +} + +impl Pair { + fn cmp_display(&self) { + if self.x >= self.y { + println!("The largest member is x = {}", self.x); + } else { + println!("The largest member is y = {}", self.y); + } + } +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt new file mode 100644 index 0000000000..5f9b71b0bf --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0597]: `x` does not live long enough + --> src/main.rs:7:17 + | +7 | r = &x; + | ^^ borrowed value does not live long enough +8 | } + | - `x` dropped here while still borrowed +9 | +10 | println!("r: {}", r); + | - borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0597`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs new file mode 100644 index 0000000000..16adb6a0d6 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + { + let r; + + { + let x = 5; + r = &x; + } + + println!("r: {}", r); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock new file mode 100644 index 0000000000..6388bb2b53 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs new file mode 100644 index 0000000000..65dbf375a8 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + { + let r; // ---------+-- 'a + // | + { // | + let x = 5; // -+-- 'b | + r = &x; // | | + } // -+ | + // | + println!("r: {}", r); // | + } // ---------+ + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock new file mode 100644 index 0000000000..6388bb2b53 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore new file mode 100644 index 0000000000..9a53c718a8 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/rustfmt-ignore @@ -0,0 +1,3 @@ +We have some weird comments pointing out borrowing scopes that we don't want to change; +unfortunately I haven't found a way to skip them with rustfmt that works so for now we're going to +manually skip those listings. See: https://github.com/rust-lang/rustfmt/issues/4028 diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs new file mode 100644 index 0000000000..94e70f00f8 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + { + let x = 5; // ----------+-- 'b + // | + let r = &x; // --+-- 'a | + // | | + println!("r: {}", r); // | | + // --+ | + } // ----------+ + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs new file mode 100644 index 0000000000..0f076a71db --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt new file mode 100644 index 0000000000..21fb936145 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0106]: missing lifetime specifier + --> src/main.rs:9:33 + | +9 | fn longest(x: &str, y: &str) -> &str { + | ^ expected lifetime parameter + | + = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs new file mode 100644 index 0000000000..6af8c9f0da --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest(x: &str, y: &str) -> &str { + if x.len() > y.len() { + x + } else { + y + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs new file mode 100644 index 0000000000..09c3a0daaa --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs new file mode 100644 index 0000000000..836ec72959 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +fn main() { + let string1 = String::from("long string is long"); + + { + let string2 = String::from("xyz"); + let result = longest(string1.as_str(), string2.as_str()); + println!("The longest string is {}", result); + } +} +// ANCHOR_END: here + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt new file mode 100644 index 0000000000..bcedda0f49 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0597]: `string2` does not live long enough + --> src/main.rs:6:44 + | +6 | result = longest(string1.as_str(), string2.as_str()); + | ^^^^^^^ borrowed value does not live long enough +7 | } + | - `string2` dropped here while still borrowed +8 | println!("The longest string is {}", result); + | ------ borrow later used here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0597`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs new file mode 100644 index 0000000000..2a6fa5898f --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs @@ -0,0 +1,19 @@ +// ANCHOR: here +fn main() { + let string1 = String::from("long string is long"); + let result; + { + let string2 = String::from("xyz"); + result = longest(string1.as_str(), string2.as_str()); + } + println!("The longest string is {}", result); +} +// ANCHOR_END: here + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs new file mode 100644 index 0000000000..2937b194ca --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs @@ -0,0 +1,11 @@ +struct ImportantExcerpt<'a> { + part: &'a str, +} + +fn main() { + let novel = String::from("Call me Ishmael. Some years ago..."); + let first_sentence = novel.split('.').next().expect("Could not find a '.'"); + let i = ImportantExcerpt { + part: first_sentence, + }; +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock new file mode 100644 index 0000000000..2aa4918e5d --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml new file mode 100644 index 0000000000..686de938f0 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs new file mode 100644 index 0000000000..431a261d2c --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs @@ -0,0 +1,29 @@ +// ANCHOR: here +fn first_word(s: &str) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[0..i]; + } + } + + &s[..] +} +// ANCHOR_END: here + +fn main() { + let my_string = String::from("hello world"); + + // first_word works on slices of `String`s + let word = first_word(&my_string[..]); + + let my_string_literal = "hello world"; + + // first_word works on slices of string literals + let word = first_word(&my_string_literal[..]); + + // Because string literals *are* string slices already, + // this works too, without the slice syntax! + let word = first_word(my_string_literal); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs new file mode 100644 index 0000000000..fa644ca4fb --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/lib.rs @@ -0,0 +1,29 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs new file mode 100644 index 0000000000..466dc4d59a --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs @@ -0,0 +1,16 @@ +use chapter10::{self, Summary, Tweet}; + +fn main() { + // ANCHOR: here + let tweet = Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + }; + + println!("1 new tweet: {}", tweet.summarize()); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs new file mode 100644 index 0000000000..b6f93a68f7 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Summary { + fn summarize(&self) -> String { + String::from("(Read more...)") + } +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle {} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs new file mode 100644 index 0000000000..44c9c64ea1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs @@ -0,0 +1,17 @@ +use chapter10::{self, NewsArticle, Summary}; + +fn main() { + // ANCHOR: here + let article = NewsArticle { + headline: String::from("Penguins win the Stanley Cup Championship!"), + location: String::from("Pittsburgh, PA, USA"), + author: String::from("Iceburgh"), + content: String::from( + "The Pittsburgh Penguins once again are the best \ + hockey team in the NHL.", + ), + }; + + println!("New article available! {}", article.summarize()); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs new file mode 100644 index 0000000000..643906f691 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs @@ -0,0 +1,24 @@ +// ANCHOR: here +pub trait Summary { + fn summarize_author(&self) -> String; + + fn summarize(&self) -> String { + format!("(Read more from {}...)", self.summarize_author()) + } +} +// ANCHOR_END: here + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +// ANCHOR: impl +impl Summary for Tweet { + fn summarize_author(&self) -> String { + format!("@{}", self.username) + } +} +// ANCHOR_END: impl diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs new file mode 100644 index 0000000000..466dc4d59a --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs @@ -0,0 +1,16 @@ +use chapter10::{self, Summary, Tweet}; + +fn main() { + // ANCHOR: here + let tweet = Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + }; + + println!("1 new tweet: {}", tweet.summarize()); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs new file mode 100644 index 0000000000..95038433e8 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs @@ -0,0 +1,35 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} + +// ANCHOR: here +pub fn notify(item: impl Summary) { + println!("Breaking news! {}", item.summarize()); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs new file mode 100644 index 0000000000..a611fce38e --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs @@ -0,0 +1,42 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} + +// ANCHOR: here +fn returns_summarizable() -> impl Summary { + Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs new file mode 100644 index 0000000000..7cd81d4c32 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs @@ -0,0 +1,56 @@ +pub trait Summary { + fn summarize(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { + fn summarize(&self) -> String { + format!("{}, by {} ({})", self.headline, self.author, self.location) + } +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { + fn summarize(&self) -> String { + format!("{}: {}", self.username, self.content) + } +} + +// ANCHOR: here +fn returns_summarizable(switch: bool) -> impl Summary { + if switch { + NewsArticle { + headline: String::from( + "Penguins win the Stanley Cup Championship!", + ), + location: String::from("Pittsburgh, PA, USA"), + author: String::from("Iceburgh"), + content: String::from( + "The Pittsburgh Penguins once again are the best \ + hockey team in the NHL.", + ), + } + } else { + Tweet { + username: String::from("horse_ebooks"), + content: String::from( + "of course, as you probably already know, people", + ), + reply: false, + retweet: false, + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt new file mode 100644 index 0000000000..ca7023f1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt @@ -0,0 +1,29 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0508]: cannot move out of type `[T]`, a non-copy slice + --> src/main.rs:2:23 + | +2 | let mut largest = list[0]; + | ^^^^^^^ + | | + | cannot move out of here + | move occurs because `list[_]` has type `T`, which does not implement the `Copy` trait + | help: consider borrowing here: `&list[0]` + +error[E0507]: cannot move out of a shared reference + --> src/main.rs:4:18 + | +4 | for &item in list { + | ----- ^^^^ + | || + | |data moved here + | |move occurs because `item` has type `T`, which does not implement the `Copy` trait + | help: consider removing the `&`: `item` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0507, E0508. +For more information about an error, try `rustc --explain E0507`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs new file mode 100644 index 0000000000..525ce815a0 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs @@ -0,0 +1,25 @@ +// ANCHOR: here +fn largest(list: &[T]) -> T { + // ANCHOR_END: here + let mut largest = list[0]; + + for &item in list { + if item > largest { + largest = item; + } + } + + largest +} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + + let result = largest(&number_list); + println!("The largest number is {}", result); + + let char_list = vec!['y', 'm', 'a', 'q']; + + let result = largest(&char_list); + println!("The largest char is {}", result); +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs new file mode 100644 index 0000000000..d144305cb0 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "efghijklmnopqrstuvwxyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest<'a>(x: &'a str, y: &str) -> &'a str { + x +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt new file mode 100644 index 0000000000..cadd5fa32c --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling chapter10 v0.1.0 (file:///projects/chapter10) +error[E0515]: cannot return value referencing local variable `result` + --> src/main.rs:11:5 + | +11 | result.as_str() + | ------^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `result` is borrowed here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0515`. +error: could not compile `chapter10`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs new file mode 100644 index 0000000000..aca4be0a78 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is {}", result); +} + +// ANCHOR: here +fn longest<'a>(x: &str, y: &str) -> &'a str { + let result = String::from("really long string"); + result.as_str() +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs new file mode 100644 index 0000000000..32ad530b51 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs @@ -0,0 +1,28 @@ +struct ImportantExcerpt<'a> { + part: &'a str, +} + +// ANCHOR: 1st +impl<'a> ImportantExcerpt<'a> { + fn level(&self) -> i32 { + 3 + } +} +// ANCHOR_END: 1st + +// ANCHOR: 3rd +impl<'a> ImportantExcerpt<'a> { + fn announce_and_return_part(&self, announcement: &str) -> &str { + println!("Attention please: {}", announcement); + self.part + } +} +// ANCHOR_END: 3rd + +fn main() { + let novel = String::from("Call me Ishmael. Some years ago..."); + let first_sentence = novel.split('.').next().expect("Could not find a '.'"); + let i = ImportantExcerpt { + part: first_sentence, + }; +} diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock new file mode 100644 index 0000000000..e8007a19be --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "chapter10" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml new file mode 100644 index 0000000000..6d5a0ff1d1 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "chapter10" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs new file mode 100644 index 0000000000..cfafa9a6d3 --- /dev/null +++ b/src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs @@ -0,0 +1,31 @@ +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest_with_an_announcement( + string1.as_str(), + string2, + "Today is someone's birthday!", + ); + println!("The longest string is {}", result); +} + +// ANCHOR: here +use std::fmt::Display; + +fn longest_with_an_announcement<'a, T>( + x: &'a str, + y: &'a str, + ann: T, +) -> &'a str +where + T: Display, +{ + println!("Announcement! {}", ann); + if x.len() > y.len() { + x + } else { + y + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/output.txt new file mode 100644 index 0000000000..aa4b0990db --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.57s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::it_works ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs new file mode 100644 index 0000000000..8e678421e9 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt new file mode 100644 index 0000000000..c39456f818 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/output.txt @@ -0,0 +1,22 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.72s + Running target/debug/deps/adder-92948b65e88960b4 + +running 2 tests +test tests::another ... FAILED +test tests::exploration ... ok + +failures: + +---- tests::another stdout ---- +thread 'main' panicked at 'Make this test fail', src/lib.rs:10:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::another + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs new file mode 100644 index 0000000000..92f315ac85 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs @@ -0,0 +1,16 @@ +// ANCHOR: here +#[cfg(test)] +mod tests { + #[test] + fn exploration() { + assert_eq!(2 + 2, 4); + } + + #[test] + fn another() { + panic!("Make this test fail"); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs new file mode 100644 index 0000000000..aad33554b9 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs @@ -0,0 +1,15 @@ +// ANCHOR: here +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/output.txt new file mode 100644 index 0000000000..241997c15a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling rectangle v0.1.0 (file:///projects/rectangle) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/rectangle-6584c4561e48942e + +running 1 test +test tests::larger_can_hold_smaller ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests rectangle + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs new file mode 100644 index 0000000000..a02395313d --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs @@ -0,0 +1,34 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn larger_can_hold_smaller() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/output.txt new file mode 100644 index 0000000000..dc1a5212e7 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.58s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs new file mode 100644 index 0000000000..534073276d --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/output.txt new file mode 100644 index 0000000000..47a50f7e1c --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished test [unoptimized + debuginfo] target(s) in 0.58s + Running target/debug/deps/guessing_game-57d70c3acb738f4d + +running 1 test +test tests::greater_than_100 ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests guessing_game + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs new file mode 100644 index 0000000000..b417302131 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs @@ -0,0 +1,28 @@ +// ANCHOR: here +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 || value > 100 { + panic!("Guess value must be between 1 and 100, got {}.", value); + } + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn greater_than_100() { + Guess::new(200); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs new file mode 100644 index 0000000000..ffa543bfb6 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs @@ -0,0 +1,37 @@ +pub struct Guess { + value: i32, +} + +// ANCHOR: here +// --snip-- +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 { + panic!( + "Guess value must be greater than or equal to 1, got {}.", + value + ); + } else if value > 100 { + panic!( + "Guess value must be less than or equal to 100, got {}.", + value + ); + } + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic(expected = "Guess value must be less than or equal to 100")] + fn greater_than_100() { + Guess::new(200); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock new file mode 100644 index 0000000000..a6d35e395a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "silly-function" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml new file mode 100644 index 0000000000..4e0f185af4 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "silly-function" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt new file mode 100644 index 0000000000..1621d796b0 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/output.txt @@ -0,0 +1,25 @@ +$ cargo test + Compiling silly-function v0.1.0 (file:///projects/silly-function) + Finished test [unoptimized + debuginfo] target(s) in 0.58s + Running target/debug/deps/silly_function-160869f38cff9166 + +running 2 tests +test tests::this_test_will_fail ... FAILED +test tests::this_test_will_pass ... ok + +failures: + +---- tests::this_test_will_fail stdout ---- +I got the value 8 +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `5`, + right: `10`', src/lib.rs:19:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::this_test_will_fail + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs new file mode 100644 index 0000000000..6fd76ce006 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs @@ -0,0 +1,21 @@ +fn prints_and_returns_10(a: i32) -> i32 { + println!("I got the value {}", a); + 10 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn this_test_will_pass() { + let value = prints_and_returns_10(4); + assert_eq!(10, value); + } + + #[test] + fn this_test_will_fail() { + let value = prints_and_returns_10(8); + assert_eq!(5, value); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/output.txt new file mode 100644 index 0000000000..59feae3241 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/output.txt @@ -0,0 +1,18 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.62s + Running target/debug/deps/adder-92948b65e88960b4 + +running 3 tests +test tests::add_three_and_two ... ok +test tests::add_two_and_two ... ok +test tests::one_hundred ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs new file mode 100644 index 0000000000..f56715263e --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs @@ -0,0 +1,23 @@ +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs new file mode 100644 index 0000000000..800b84f53b --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs @@ -0,0 +1,21 @@ +// ANCHOR: here +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/output.txt new file mode 100644 index 0000000000..e213b9c38d --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.73s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::internal ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/integration_test-82e7799c1bc62298 + +running 1 test +test it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs new file mode 100644 index 0000000000..e26fa71096 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs @@ -0,0 +1,6 @@ +use adder; + +#[test] +fn it_adds_two() { + assert_eq!(4, adder::add_two(2)); +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt new file mode 100644 index 0000000000..0f287fc564 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.59s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::exploration ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs new file mode 100644 index 0000000000..2974d7273d --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +#[cfg(test)] +mod tests { + #[test] + fn exploration() { + assert_eq!(2 + 2, 4); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt new file mode 100644 index 0000000000..e95f4727e0 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt @@ -0,0 +1,17 @@ +$ cargo test + Compiling rectangle v0.1.0 (file:///projects/rectangle) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/rectangle-6584c4561e48942e + +running 2 tests +test tests::larger_can_hold_smaller ... ok +test tests::smaller_cannot_hold_larger ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests rectangle + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs new file mode 100644 index 0000000000..338ad09364 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs @@ -0,0 +1,51 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn larger_can_hold_smaller() { + // --snip-- + // ANCHOR_END: here + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + // ANCHOR: here + } + + #[test] + fn smaller_cannot_hold_larger() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(!smaller.can_hold(&larger)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock new file mode 100644 index 0000000000..9dcd5439df --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "rectangle" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml new file mode 100644 index 0000000000..32efee50ad --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "rectangle" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt new file mode 100644 index 0000000000..8f050a252d --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt @@ -0,0 +1,22 @@ +$ cargo test + Compiling rectangle v0.1.0 (file:///projects/rectangle) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/rectangle-6584c4561e48942e + +running 2 tests +test tests::larger_can_hold_smaller ... FAILED +test tests::smaller_cannot_hold_larger ... ok + +failures: + +---- tests::larger_can_hold_smaller stdout ---- +thread 'main' panicked at 'assertion failed: larger.can_hold(&smaller)', src/lib.rs:28:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::larger_can_hold_smaller + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs new file mode 100644 index 0000000000..33a2dd0ac1 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs @@ -0,0 +1,49 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +// ANCHOR: here +// --snip-- +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width < other.width && self.height > other.height + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn larger_can_hold_smaller() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + } + + #[test] + fn smaller_cannot_hold_larger() { + let larger = Rectangle { + width: 8, + height: 7, + }; + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(!smaller.can_hold(&larger)); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt new file mode 100644 index 0000000000..7fb67743eb --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.61s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::it_adds_two ... FAILED + +failures: + +---- tests::it_adds_two stdout ---- +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `4`, + right: `5`', src/lib.rs:11:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::it_adds_two + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs new file mode 100644 index 0000000000..8b4534b4aa --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +pub fn add_two(a: i32) -> i32 { + a + 3 +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock new file mode 100644 index 0000000000..9a7ecdd9f2 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "greeter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml new file mode 100644 index 0000000000..c289e837ab --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "greeter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs new file mode 100644 index 0000000000..4fcdbbf279 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +pub fn greeting(name: &str) -> String { + format!("Hello {}!", name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn greeting_contains_name() { + let result = greeting("Carol"); + assert!(result.contains("Carol")); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock new file mode 100644 index 0000000000..9a7ecdd9f2 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "greeter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml new file mode 100644 index 0000000000..c289e837ab --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "greeter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt new file mode 100644 index 0000000000..8f832a7432 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling greeter v0.1.0 (file:///projects/greeter) + Finished test [unoptimized + debuginfo] target(s) in 0.91s + Running target/debug/deps/greeter-170b942eb5bf5e3a + +running 1 test +test tests::greeting_contains_name ... FAILED + +failures: + +---- tests::greeting_contains_name stdout ---- +thread 'main' panicked at 'assertion failed: result.contains("Carol")', src/lib.rs:12:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::greeting_contains_name + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs new file mode 100644 index 0000000000..d516534e59 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs @@ -0,0 +1,18 @@ +// ANCHOR: here +pub fn greeting(name: &str) -> String { + String::from("Hello!") +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn greeting_contains_name() { + let result = greeting("Carol"); + assert!(result.contains("Carol")); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock new file mode 100644 index 0000000000..9a7ecdd9f2 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "greeter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml new file mode 100644 index 0000000000..c289e837ab --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "greeter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt new file mode 100644 index 0000000000..c3a735e4d4 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling greeter v0.1.0 (file:///projects/greeter) + Finished test [unoptimized + debuginfo] target(s) in 0.93s + Running target/debug/deps/greeter-170b942eb5bf5e3a + +running 1 test +test tests::greeting_contains_name ... FAILED + +failures: + +---- tests::greeting_contains_name stdout ---- +thread 'main' panicked at 'Greeting did not contain name, value was `Hello!`', src/lib.rs:12:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::greeting_contains_name + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs new file mode 100644 index 0000000000..519c7a4c6f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs @@ -0,0 +1,20 @@ +pub fn greeting(name: &str) -> String { + String::from("Hello!") +} + +#[cfg(test)] +mod tests { + use super::*; + + // ANCHOR: here + #[test] + fn greeting_contains_name() { + let result = greeting("Carol"); + assert!( + result.contains("Carol"), + "Greeting did not contain name, value was `{}`", + result + ); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt new file mode 100644 index 0000000000..c9a4fda931 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt @@ -0,0 +1,19 @@ +$ cargo test + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished test [unoptimized + debuginfo] target(s) in 0.62s + Running target/debug/deps/guessing_game-57d70c3acb738f4d + +running 1 test +test tests::greater_than_100 ... FAILED + +failures: + +---- tests::greater_than_100 stdout ---- +note: test did not panic as expected + +failures: + tests::greater_than_100 + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs new file mode 100644 index 0000000000..269c73cefa --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs @@ -0,0 +1,29 @@ +pub struct Guess { + value: i32, +} + +// ANCHOR: here +// --snip-- +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 { + panic!("Guess value must be between 1 and 100, got {}.", value); + } + + Guess { value } + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn greater_than_100() { + Guess::new(200); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock new file mode 100644 index 0000000000..5802b7dc9a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "guessing_game" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml new file mode 100644 index 0000000000..922762ab1f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "guessing_game" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt new file mode 100644 index 0000000000..f2b8ffc7c3 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) + Finished test [unoptimized + debuginfo] target(s) in 0.66s + Running target/debug/deps/guessing_game-57d70c3acb738f4d + +running 1 test +test tests::greater_than_100 ... FAILED + +failures: + +---- tests::greater_than_100 stdout ---- +thread 'main' panicked at 'Guess value must be greater than or equal to 1, got 200.', src/lib.rs:13:13 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. +note: panic did not contain expected string + panic message: `"Guess value must be greater than or equal to 1, got 200."`, + expected substring: `"Guess value must be less than or equal to 100"` + +failures: + tests::greater_than_100 + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs new file mode 100644 index 0000000000..21650040da --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs @@ -0,0 +1,34 @@ +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + // ANCHOR: here + if value < 1 { + panic!( + "Guess value must be less than or equal to 100, got {}.", + value + ); + } else if value > 100 { + panic!( + "Guess value must be greater than or equal to 1, got {}.", + value + ); + } + // ANCHOR_END: here + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic(expected = "Guess value must be less than or equal to 100")] + fn greater_than_100() { + Guess::new(200); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs new file mode 100644 index 0000000000..6284f4f291 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs @@ -0,0 +1,11 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() -> Result<(), String> { + if 2 + 2 == 4 { + Ok(()) + } else { + Err(String::from("two plus two does not equal four")) + } + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt new file mode 100644 index 0000000000..8cf7475c5e --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt @@ -0,0 +1,17 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.60s + Running target/debug/deps/adder-92948b65e88960b4 + +running 2 tests +test expensive_test ... ignored +test it_works ... ok + +test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs new file mode 100644 index 0000000000..9a75301e31 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +#[test] +fn it_works() { + assert_eq!(2 + 2, 4); +} + +#[test] +#[ignore] +fn expensive_test() { + // code that takes an hour to run +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt new file mode 100644 index 0000000000..0637a1068f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt @@ -0,0 +1,29 @@ +$ cargo test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.89s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::internal ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/common-7064e1b6d2e271be + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/integration_test-82e7799c1bc62298 + +running 1 test +test it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs new file mode 100644 index 0000000000..5fb7a390a6 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs @@ -0,0 +1,3 @@ +pub fn setup() { + // setup code specific to your library's tests would go here +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs new file mode 100644 index 0000000000..e26fa71096 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/integration_test.rs @@ -0,0 +1,6 @@ +use adder; + +#[test] +fn it_adds_two() { + assert_eq!(4, adder::add_two(2)); +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs new file mode 100644 index 0000000000..5fb7a390a6 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub fn setup() { + // setup code specific to your library's tests would go here +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs new file mode 100644 index 0000000000..58b8b7b89b --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs @@ -0,0 +1,9 @@ +use adder; + +mod common; + +#[test] +fn it_adds_two() { + common::setup(); + assert_eq!(4, adder::add_two(2)); +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock new file mode 100644 index 0000000000..a6d35e395a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "silly-function" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml new file mode 100644 index 0000000000..4e0f185af4 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "silly-function" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt new file mode 100644 index 0000000000..901df6ae63 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt @@ -0,0 +1,34 @@ +$ cargo test -- --show-output + Compiling silly-function v0.1.0 (file:///projects/silly-function) + Finished test [unoptimized + debuginfo] target(s) in 0.60s + Running target/debug/deps/silly_function-160869f38cff9166 + +running 2 tests +test tests::this_test_will_fail ... FAILED +test tests::this_test_will_pass ... ok + +successes: + +---- tests::this_test_will_pass stdout ---- +I got the value 4 + + +successes: + tests::this_test_will_pass + +failures: + +---- tests::this_test_will_fail stdout ---- +I got the value 8 +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `5`, + right: `10`', src/lib.rs:19:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::this_test_will_fail + +test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs new file mode 100644 index 0000000000..43c4c92f9a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-01-show-output/src/lib.rs @@ -0,0 +1,21 @@ +pub fn prints_and_returns_10(a: i32) -> i32 { + println!("I got the value {}", a); + 10 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn this_test_will_pass() { + let value = prints_and_returns_10(4); + assert_eq!(10, value); + } + + #[test] + fn this_test_will_fail() { + let value = prints_and_returns_10(8); + assert_eq!(5, value); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt new file mode 100644 index 0000000000..9284de3d4f --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt @@ -0,0 +1,10 @@ +$ cargo test one_hundred + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.69s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test tests::one_hundred ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs new file mode 100644 index 0000000000..f56715263e --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-02-single-test/src/lib.rs @@ -0,0 +1,23 @@ +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt new file mode 100644 index 0000000000..76c2c170df --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt @@ -0,0 +1,11 @@ +$ cargo test add + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.61s + Running target/debug/deps/adder-92948b65e88960b4 + +running 2 tests +test tests::add_three_and_two ... ok +test tests::add_two_and_two ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs new file mode 100644 index 0000000000..f56715263e --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-03-multiple-tests/src/lib.rs @@ -0,0 +1,23 @@ +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt new file mode 100644 index 0000000000..6bddfdb820 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt @@ -0,0 +1,16 @@ +$ cargo test -- --ignored + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.61s + Running target/debug/deps/adder-92948b65e88960b4 + +running 1 test +test expensive_test ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out + + Doc-tests adder + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs new file mode 100644 index 0000000000..9a75301e31 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-04-running-ignored/src/lib.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +#[test] +fn it_works() { + assert_eq!(2 + 2, 4); +} + +#[test] +#[ignore] +fn expensive_test() { + // code that takes an hour to run +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt new file mode 100644 index 0000000000..dd915c35c1 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt @@ -0,0 +1,10 @@ +$ cargo test --test integration_test + Compiling adder v0.1.0 (file:///projects/adder) + Finished test [unoptimized + debuginfo] target(s) in 0.64s + Running target/debug/deps/integration_test-82e7799c1bc62298 + +running 1 test +test it_adds_two ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs new file mode 100644 index 0000000000..c3961b1f62 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/src/lib.rs @@ -0,0 +1,17 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs new file mode 100644 index 0000000000..e26fa71096 --- /dev/null +++ b/src/doc/book/listings/ch11-writing-automated-tests/output-only-05-single-integration/tests/integration_test.rs @@ -0,0 +1,6 @@ +use adder; + +#[test] +fn it_adds_two() { + assert_eq!(4, adder::add_two(2)); +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-01/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-01/output.txt new file mode 100644 index 0000000000..d0ef998122 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-01/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.61s + Running `target/debug/minigrep` +["target/debug/minigrep"] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-01/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-01/src/main.rs new file mode 100644 index 0000000000..aa3056de60 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-01/src/main.rs @@ -0,0 +1,6 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + println!("{:?}", args); +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-02/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-02/output.txt new file mode 100644 index 0000000000..f759eea008 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-02/output.txt @@ -0,0 +1,6 @@ +$ cargo run test sample.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep test sample.txt` +Searching for test +In file sample.txt diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-02/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-02/src/main.rs new file mode 100644 index 0000000000..8daf125c67 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-02/src/main.rs @@ -0,0 +1,11 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + let query = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", query); + println!("In file {}", filename); +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-03/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-03/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-03/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-03/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-03/src/main.rs new file mode 100644 index 0000000000..8daf125c67 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-03/src/main.rs @@ -0,0 +1,11 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + + let query = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", query); + println!("In file {}", filename); +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-04/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-04/output.txt new file mode 100644 index 0000000000..75e7863ef5 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-04/output.txt @@ -0,0 +1,17 @@ +$ cargo run the poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep the poem.txt` +Searching for the +In file poem.txt +With text: +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-04/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-04/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-04/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-04/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-04/src/main.rs new file mode 100644 index 0000000000..9a0eade562 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-04/src/main.rs @@ -0,0 +1,22 @@ +// ANCHOR: here +use std::env; +use std::fs; + +fn main() { + // --snip-- + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let query = &args[1]; + let filename = &args[2]; + + println!("Searching for {}", query); + // ANCHOR: here + println!("In file {}", filename); + + let contents = fs::read_to_string(filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-05/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-05/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-05/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-05/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-05/src/main.rs new file mode 100644 index 0000000000..fb8805687e --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-05/src/main.rs @@ -0,0 +1,29 @@ +use std::env; +use std::fs; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let (query, filename) = parse_config(&args); + + // --snip-- + // ANCHOR_END: here + + println!("Searching for {}", query); + println!("In file {}", filename); + + let contents = fs::read_to_string(filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); + // ANCHOR: here +} + +fn parse_config(args: &[String]) -> (&str, &str) { + let query = &args[1]; + let filename = &args[2]; + + (query, filename) +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-06/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-06/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-06/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-06/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-06/src/main.rs new file mode 100644 index 0000000000..b5d89bc98f --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-06/src/main.rs @@ -0,0 +1,34 @@ +use std::env; +use std::fs; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let config = parse_config(&args); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + // --snip-- + // ANCHOR_END: here + + println!("With text:\n{}", contents); + // ANCHOR: here +} + +struct Config { + query: String, + filename: String, +} + +fn parse_config(args: &[String]) -> Config { + let query = args[1].clone(); + let filename = args[2].clone(); + + Config { query, filename } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-07/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-07/output.txt new file mode 100644 index 0000000000..8c8d53aa8b --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-07/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep` +thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', src/main.rs:27:21 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-07/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-07/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-07/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-07/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-07/src/main.rs new file mode 100644 index 0000000000..36d35ceafb --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-07/src/main.rs @@ -0,0 +1,40 @@ +use std::env; +use std::fs; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + // ANCHOR_END: here + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); + // ANCHOR: here + + // --snip-- +} + +// --snip-- + +// ANCHOR_END: here +struct Config { + query: String, + filename: String, +} + +// ANCHOR: here +impl Config { + fn new(args: &[String]) -> Config { + let query = args[1].clone(); + let filename = args[2].clone(); + + Config { query, filename } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-08/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-08/output.txt new file mode 100644 index 0000000000..fa5d235eb5 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-08/output.txt @@ -0,0 +1,6 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep` +thread 'main' panicked at 'not enough arguments', src/main.rs:26:13 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-08/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-08/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-08/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-08/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-08/src/main.rs new file mode 100644 index 0000000000..dddf10bd44 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-08/src/main.rs @@ -0,0 +1,38 @@ +use std::env; +use std::fs; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +struct Config { + query: String, + filename: String, +} + +impl Config { + // ANCHOR: here + // --snip-- + fn new(args: &[String]) -> Config { + if args.len() < 3 { + panic!("not enough arguments"); + } + // --snip-- + // ANCHOR_END: here + + let query = args[1].clone(); + let filename = args[2].clone(); + + Config { query, filename } + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-09/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-09/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-09/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-09/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-09/src/main.rs new file mode 100644 index 0000000000..83f46ee37f --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-09/src/main.rs @@ -0,0 +1,36 @@ +use std::env; +use std::fs; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +struct Config { + query: String, + filename: String, +} + +// ANCHOR: here +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-10/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-10/output.txt new file mode 100644 index 0000000000..7aad57f52d --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-10/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/minigrep` +Problem parsing arguments: not enough arguments diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-10/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-10/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-10/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-10/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-10/src/main.rs new file mode 100644 index 0000000000..c8aeb1d37e --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-10/src/main.rs @@ -0,0 +1,42 @@ +use std::env; +use std::fs; +// ANCHOR: here +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // --snip-- + // ANCHOR_END: here + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-11/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-11/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-11/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-11/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-11/src/main.rs new file mode 100644 index 0000000000..974b503b72 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-11/src/main.rs @@ -0,0 +1,50 @@ +use std::env; +use std::fs; +use std::process; + +// ANCHOR: here +fn main() { + // --snip-- + + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // ANCHOR: here + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + run(config); +} + +fn run(config: Config) { + let contents = fs::read_to_string(config.filename) + .expect("Something went wrong reading the file"); + + println!("With text:\n{}", contents); +} + +// --snip-- +// ANCHOR_END: here + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-12/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-12/output.txt new file mode 100644 index 0000000000..565479d0c8 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-12/output.txt @@ -0,0 +1,26 @@ +$ cargo run the poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) +warning: unused `std::result::Result` that must be used + --> src/main.rs:19:5 + | +19 | run(config); + | ^^^^^^^^^^^^ + | + = note: `#[warn(unused_must_use)]` on by default + = note: this `Result` may be an `Err` variant, which should be handled + + Finished dev [unoptimized + debuginfo] target(s) in 0.71s + Running `target/debug/minigrep the poem.txt` +Searching for the +In file poem.txt +With text: +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-12/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-12/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-12/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-12/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-12/src/main.rs new file mode 100644 index 0000000000..f2e0e6b9f3 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-12/src/main.rs @@ -0,0 +1,51 @@ +use std::env; +use std::fs; +use std::process; +// ANCHOR: here +use std::error::Error; + +// --snip-- + +// ANCHOR_END: here + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + run(config); +} + +// ANCHOR: here +fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} +// ANCHOR_END: here + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-13/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-13/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-13/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-13/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-13/src/lib.rs new file mode 100644 index 0000000000..5b2850a5df --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-13/src/lib.rs @@ -0,0 +1,36 @@ +// ANCHOR: here +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + // --snip-- + // ANCHOR_END: here + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + // ANCHOR: here + } +} + +pub fn run(config: Config) -> Result<(), Box> { + // --snip-- + // ANCHOR_END: here + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-13/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-13/src/main.rs new file mode 100644 index 0000000000..b2447dce97 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-13/src/main.rs @@ -0,0 +1,20 @@ +use std::env; +use std::process; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-14/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-14/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-14/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-14/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-14/src/lib.rs new file mode 100644 index 0000000000..2ba2fd1961 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-14/src/lib.rs @@ -0,0 +1,28 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-14/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-14/src/main.rs new file mode 100644 index 0000000000..5eb4024f5c --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-14/src/main.rs @@ -0,0 +1,30 @@ +// ANCHOR: here +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + // --snip-- + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + // ANCHOR: here + if let Err(e) = minigrep::run(config) { + // --snip-- + // ANCHOR_END: here + println!("Application error: {}", e); + + process::exit(1); + // ANCHOR: here + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-15/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-15/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-15/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-15/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-15/src/lib.rs new file mode 100644 index 0000000000..22ec381783 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-15/src/lib.rs @@ -0,0 +1,46 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-15/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-15/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-15/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt new file mode 100644 index 0000000000..a7a676ec3d --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished test [unoptimized + debuginfo] target(s) in 0.97s + Running target/debug/deps/minigrep-4672b652f7794785 + +running 1 test +test tests::one_result ... FAILED + +failures: + +---- tests::one_result stdout ---- +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `["safe, fast, productive."]`, + right: `[]`', src/lib.rs:44:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::one_result + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-16/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-16/src/lib.rs new file mode 100644 index 0000000000..2fc5b4f722 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/src/lib.rs @@ -0,0 +1,50 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + vec![] +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-16/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-16/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-16/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-17/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-17/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-17/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-17/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-17/src/lib.rs new file mode 100644 index 0000000000..0b094ce28a --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-17/src/lib.rs @@ -0,0 +1,50 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + // do something with line + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-17/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-17/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-17/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-18/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-18/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-18/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-18/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-18/src/lib.rs new file mode 100644 index 0000000000..c9d1f529da --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-18/src/lib.rs @@ -0,0 +1,52 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + for line in contents.lines() { + if line.contains(query) { + // do something with line + } + } +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-18/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-18/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-18/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-19/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-19/output.txt new file mode 100644 index 0000000000..fa1490152a --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-19/output.txt @@ -0,0 +1,22 @@ +$ cargo test + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished test [unoptimized + debuginfo] target(s) in 1.22s + Running target/debug/deps/minigrep-4672b652f7794785 + +running 1 test +test tests::one_result ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/minigrep-caf9dbee196c78b9 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests minigrep + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-19/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-19/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-19/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-19/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-19/src/lib.rs new file mode 100644 index 0000000000..de8897b8d1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-19/src/lib.rs @@ -0,0 +1,58 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +// ANCHOR: ch13 +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} +// ANCHOR_END: ch13 +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-19/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-19/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-19/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-20/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-20/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-20/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-20/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-20/src/lib.rs new file mode 100644 index 0000000000..52ba2bd51c --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-20/src/lib.rs @@ -0,0 +1,78 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-20/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-20/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-20/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-21/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-21/output.txt new file mode 100644 index 0000000000..3d7cf26d1f --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-21/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished test [unoptimized + debuginfo] target(s) in 1.33s + Running target/debug/deps/minigrep-4672b652f7794785 + +running 2 tests +test tests::case_insensitive ... ok +test tests::case_sensitive ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Running target/debug/deps/minigrep-caf9dbee196c78b9 + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + + Doc-tests minigrep + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-21/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-21/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-21/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-21/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-21/src/lib.rs new file mode 100644 index 0000000000..873c8b53d0 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-21/src/lib.rs @@ -0,0 +1,94 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +// ANCHOR: here +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-21/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-21/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-21/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-22/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-22/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-22/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-22/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-22/src/lib.rs new file mode 100644 index 0000000000..2df82b7e2f --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-22/src/lib.rs @@ -0,0 +1,103 @@ +use std::error::Error; +use std::fs; + +// ANCHOR: here +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} +// ANCHOR_END: here + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: there +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: there + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-22/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-22/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-22/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-23/output.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-23/output.txt new file mode 100644 index 0000000000..0f0f07f751 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-23/output.txt @@ -0,0 +1,6 @@ +$ cargo run to poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep to poem.txt` +Are you nobody, too? +How dreary to be somebody! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-23/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-23/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-23/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-23/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-23/src/lib.rs new file mode 100644 index 0000000000..e6dc51a0ed --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-23/src/lib.rs @@ -0,0 +1,112 @@ +// ANCHOR: here +use std::env; +// --snip-- + +// ANCHOR_END: here +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: here +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} +// ANCHOR_END: here + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-23/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-23/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-23/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-24/poem.txt b/src/doc/book/listings/ch12-an-io-project/listing-12-24/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-24/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-24/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-24/src/lib.rs new file mode 100644 index 0000000000..fe1dccf4ee --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-24/src/lib.rs @@ -0,0 +1,104 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/listing-12-24/src/main.rs b/src/doc/book/listings/ch12-an-io-project/listing-12-24/src/main.rs new file mode 100644 index 0000000000..9e38553c56 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/listing-12-24/src/main.rs @@ -0,0 +1,21 @@ +use std::env; +use std::process; + +use minigrep::Config; + +// ANCHOR: here +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs new file mode 100644 index 0000000000..44bcfeab30 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs @@ -0,0 +1,54 @@ +use std::env; +use std::error::Error; +use std::fs; +use std::process; + +// ANCHOR: here +fn main() { + // --snip-- + + // ANCHOR_END: here + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // ANCHOR: here + println!("Searching for {}", config.query); + println!("In file {}", config.filename); + + if let Err(e) = run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} +// ANCHOR_END: here + +fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + println!("With text:\n{}", contents); + + Ok(()) +} + +struct Config { + query: String, + filename: String, +} + +impl Config { + fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt new file mode 100644 index 0000000000..91532d0cd5 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/output.txt @@ -0,0 +1,5 @@ +$ cargo run frog poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.38s + Running `target/debug/minigrep frog poem.txt` +How public, like a frog diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs new file mode 100644 index 0000000000..ede4eb49a0 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/lib.rs @@ -0,0 +1,60 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: here +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: here + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/no-listing-02-using-search-in-run/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/output.txt b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/output.txt new file mode 100644 index 0000000000..eb88d9a9b1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/output.txt @@ -0,0 +1,5 @@ +$ cargo run needle haystack + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 1.57s + Running `target/debug/minigrep needle haystack` +["target/debug/minigrep", "needle", "haystack"] diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs new file mode 100644 index 0000000000..aa3056de60 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-01-with-args/src/main.rs @@ -0,0 +1,6 @@ +use std::env; + +fn main() { + let args: Vec = env::args().collect(); + println!("{:?}", args); +} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt new file mode 100644 index 0000000000..b76084b0f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt @@ -0,0 +1,16 @@ +$ cargo build + Compiling minigrep v0.1.0 (file:///projects/minigrep) +error[E0106]: missing lifetime specifier + --> src/lib.rs:28:51 + | +28 | pub fn search(query: &str, contents: &str) -> Vec<&str> { + | ^ expected lifetime parameter + | + = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0106`. +error: could not compile `minigrep`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs new file mode 100644 index 0000000000..c60405c219 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/lib.rs @@ -0,0 +1,50 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + Ok(()) +} + +// ANCHOR: here +pub fn search(query: &str, contents: &str) -> Vec<&str> { + vec![] +} +// ANCHOR_END: here + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-02-missing-lifetimes/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt new file mode 100644 index 0000000000..c0ab7efd97 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/output.txt @@ -0,0 +1,7 @@ +$ cargo run body poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep body poem.txt` +I’m nobody! Who are you? +Are you nobody, too? +How dreary to be somebody! diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs new file mode 100644 index 0000000000..ede4eb49a0 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/lib.rs @@ -0,0 +1,60 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: here +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: here + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-03-multiple-matches/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/output.txt b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/output.txt new file mode 100644 index 0000000000..4cd6c8a0ae --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/output.txt @@ -0,0 +1,4 @@ +$ cargo run monomorphization poem.txt + Compiling minigrep v0.1.0 (file:///projects/minigrep) + Finished dev [unoptimized + debuginfo] target(s) in 0.0s + Running `target/debug/minigrep monomorphization poem.txt` diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt new file mode 100644 index 0000000000..208e35a5ec --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/poem.txt @@ -0,0 +1,9 @@ +I’m nobody! Who are you? +Are you nobody, too? +Then there’s a pair of us - don’t tell! +They’d banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs new file mode 100644 index 0000000000..ede4eb49a0 --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/lib.rs @@ -0,0 +1,60 @@ +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + Ok(Config { query, filename }) + } +} + +// ANCHOR: here +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + for line in search(&config.query, &contents) { + println!("{}", line); + } + + Ok(()) +} +// ANCHOR_END: here + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_result() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } +} diff --git a/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch12-an-io-project/output-only-04-no-matches/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs new file mode 100644 index 0000000000..5397d7f617 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs @@ -0,0 +1,108 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: ch13 +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} +// ANCHOR_END: ch13 + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs new file mode 100644 index 0000000000..53af83fdbc --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-23-reproduced/src/main.rs @@ -0,0 +1,19 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + println!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + println!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs new file mode 100644 index 0000000000..fe1dccf4ee --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/lib.rs @@ -0,0 +1,104 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs new file mode 100644 index 0000000000..ec27e67f99 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs @@ -0,0 +1,25 @@ +use std::env; +use std::process; + +use minigrep::Config; + +// ANCHOR: ch13 +fn main() { + let args: Vec = env::args().collect(); + + let config = Config::new(&args).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // --snip-- + // ANCHOR_END: ch13 + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } + // ANCHOR: ch13 +} +// ANCHOR_END: ch13 diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-01/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-01/src/main.rs new file mode 100644 index 0000000000..97eace01d7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-01/src/main.rs @@ -0,0 +1,12 @@ +// ANCHOR: here +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-02/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-02/src/main.rs new file mode 100644 index 0000000000..96d06c77d4 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-02/src/main.rs @@ -0,0 +1,19 @@ +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} + +fn generate_workout(intensity: u32, random_number: u32) {} + +// ANCHOR: here +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-03/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-03/src/main.rs new file mode 100644 index 0000000000..d43c9b2116 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-03/src/main.rs @@ -0,0 +1,39 @@ +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + if intensity < 25 { + println!( + "Today, do {} pushups!", + simulated_expensive_calculation(intensity) + ); + println!( + "Next, do {} situps!", + simulated_expensive_calculation(intensity) + ); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + simulated_expensive_calculation(intensity) + ); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-04/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-04/src/main.rs new file mode 100644 index 0000000000..fabe0fb01d --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-04/src/main.rs @@ -0,0 +1,32 @@ +use std::thread; +use std::time::Duration; + +fn simulated_expensive_calculation(intensity: u32) -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + intensity +} + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + let expensive_result = simulated_expensive_calculation(intensity); + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_result); + println!("Next, do {} situps!", expensive_result); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!("Today, run for {} minutes!", expensive_result); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-05/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-05/src/main.rs new file mode 100644 index 0000000000..6984a27a0e --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-05/src/main.rs @@ -0,0 +1,33 @@ +use std::thread; +use std::time::Duration; + +fn generate_workout(intensity: u32, random_number: u32) { + // ANCHOR: here + let expensive_closure = |num| { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }; + // ANCHOR_END: here + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_closure(intensity)); + println!("Next, do {} situps!", expensive_closure(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_closure(intensity) + ); + } + } +} + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-06/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-06/src/main.rs new file mode 100644 index 0000000000..8850e58a76 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-06/src/main.rs @@ -0,0 +1,33 @@ +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + let expensive_closure = |num| { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }; + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_closure(intensity)); + println!("Next, do {} situps!", expensive_closure(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_closure(intensity) + ); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-07/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-07/src/main.rs new file mode 100644 index 0000000000..b3f4cc2c2a --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-07/src/main.rs @@ -0,0 +1,33 @@ +use std::thread; +use std::time::Duration; + +fn generate_workout(intensity: u32, random_number: u32) { + // ANCHOR: here + let expensive_closure = |num: u32| -> u32 { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }; + // ANCHOR_END: here + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_closure(intensity)); + println!("Next, do {} situps!", expensive_closure(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_closure(intensity) + ); + } + } +} + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.lock new file mode 100644 index 0000000000..c190d3a411 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "closure-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.toml new file mode 100644 index 0000000000..54b904e411 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "closure-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt b/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt new file mode 100644 index 0000000000..d859957f21 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-08/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling closure-example v0.1.0 (file:///projects/closure-example) +error[E0308]: mismatched types + --> src/main.rs:5:29 + | +5 | let n = example_closure(5); + | ^ + | | + | expected struct `std::string::String`, found integer + | help: try using a conversion method: `5.to_string()` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `closure-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-08/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-08/src/main.rs new file mode 100644 index 0000000000..ebb2489bf7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-08/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let example_closure = |x| x; + + let s = example_closure(String::from("hello")); + let n = example_closure(5); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.lock new file mode 100644 index 0000000000..e090432bc9 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cacher" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.toml new file mode 100644 index 0000000000..54ab6f2173 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cacher" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-09/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-09/src/main.rs new file mode 100644 index 0000000000..3fd4ed067f --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-09/src/main.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.lock new file mode 100644 index 0000000000..e090432bc9 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cacher" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.toml new file mode 100644 index 0000000000..54ab6f2173 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cacher" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-10/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-10/src/main.rs new file mode 100644 index 0000000000..4d1034db94 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-10/src/main.rs @@ -0,0 +1,34 @@ +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +// ANCHOR: here +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + Cacher { + calculation, + value: None, + } + } + + fn value(&mut self, arg: u32) -> u32 { + match self.value { + Some(v) => v, + None => { + let v = (self.calculation)(arg); + self.value = Some(v); + v + } + } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.lock new file mode 100644 index 0000000000..75ff09e51b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "workout-app" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.toml new file mode 100644 index 0000000000..8e64540e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "workout-app" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-11/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-11/src/main.rs new file mode 100644 index 0000000000..9f378b7935 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-11/src/main.rs @@ -0,0 +1,64 @@ +use std::thread; +use std::time::Duration; + +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + Cacher { + calculation, + value: None, + } + } + + fn value(&mut self, arg: u32) -> u32 { + match self.value { + Some(v) => v, + None => { + let v = (self.calculation)(arg); + self.value = Some(v); + v + } + } + } +} + +// ANCHOR: here +fn generate_workout(intensity: u32, random_number: u32) { + let mut expensive_result = Cacher::new(|num| { + println!("calculating slowly..."); + thread::sleep(Duration::from_secs(2)); + num + }); + + if intensity < 25 { + println!("Today, do {} pushups!", expensive_result.value(intensity)); + println!("Next, do {} situps!", expensive_result.value(intensity)); + } else { + if random_number == 3 { + println!("Take a break today! Remember to stay hydrated!"); + } else { + println!( + "Today, run for {} minutes!", + expensive_result.value(intensity) + ); + } + } +} +// ANCHOR_END: here + +fn main() { + let simulated_user_specified_value = 10; + let simulated_random_number = 7; + + generate_workout(simulated_user_specified_value, simulated_random_number); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.lock new file mode 100644 index 0000000000..a96532addb --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "equal-to-x" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.toml new file mode 100644 index 0000000000..4fd5d85234 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "equal-to-x" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-12/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-12/src/main.rs new file mode 100644 index 0000000000..7352b80b23 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-12/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let x = 4; + + let equal_to_x = |z| z == x; + + let y = 4; + + assert!(equal_to_x(y)); +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-13/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-13/src/main.rs new file mode 100644 index 0000000000..55a0dd37e9 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-13/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let v1 = vec![1, 2, 3]; + + let v1_iter = v1.iter(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-14/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-14/src/main.rs new file mode 100644 index 0000000000..712aff4085 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-14/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let v1 = vec![1, 2, 3]; + + let v1_iter = v1.iter(); + + for val in v1_iter { + println!("Got: {}", val); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-15/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-15/src/lib.rs new file mode 100644 index 0000000000..afea80d22e --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-15/src/lib.rs @@ -0,0 +1,18 @@ +#[cfg(test)] +mod tests { + // ANCHOR: here + #[test] + fn iterator_demonstration() { + let v1 = vec![1, 2, 3]; + + let mut v1_iter = v1.iter(); + + assert_eq!(v1_iter.next(), Some(&1)); + assert_eq!(v1_iter.next(), Some(&2)); + assert_eq!(v1_iter.next(), Some(&3)); + assert_eq!(v1_iter.next(), None); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-16/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-16/src/lib.rs new file mode 100644 index 0000000000..198b3c834b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-16/src/lib.rs @@ -0,0 +1,17 @@ +#[cfg(test)] +mod tests { + // ANCHOR: here + #[test] + fn iterator_sum() { + let v1 = vec![1, 2, 3]; + + let v1_iter = v1.iter(); + + let total: i32 = v1_iter.sum(); + + assert_eq!(total, 6); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-17/output.txt b/src/doc/book/listings/ch13-functional-features/listing-13-17/output.txt new file mode 100644 index 0000000000..ff02254be7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-17/output.txt @@ -0,0 +1,13 @@ +$ cargo run + Compiling iterators v0.1.0 (file:///projects/iterators) +warning: unused `std::iter::Map` that must be used + --> src/main.rs:4:5 + | +4 | v1.iter().map(|x| x + 1); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_must_use)]` on by default + = note: iterators are lazy and do nothing unless consumed + + Finished dev [unoptimized + debuginfo] target(s) in 0.47s + Running `target/debug/iterators` diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-17/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-17/src/main.rs new file mode 100644 index 0000000000..62a68be9b3 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-17/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let v1: Vec = vec![1, 2, 3]; + + v1.iter().map(|x| x + 1); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.lock new file mode 100644 index 0000000000..e91eaa8d4c --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "iterators" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.toml new file mode 100644 index 0000000000..015f9512f7 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "iterators" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-18/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-18/src/main.rs new file mode 100644 index 0000000000..db9025d6fd --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-18/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let v1: Vec = vec![1, 2, 3]; + + let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); + + assert_eq!(v2, vec![2, 3, 4]); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.lock new file mode 100644 index 0000000000..0b15e2157a --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shoe_size" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.toml new file mode 100644 index 0000000000..d0ecdac67b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shoe_size" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-19/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-19/src/lib.rs new file mode 100644 index 0000000000..c7ca364c28 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-19/src/lib.rs @@ -0,0 +1,50 @@ +#[derive(PartialEq, Debug)] +struct Shoe { + size: u32, + style: String, +} + +fn shoes_in_my_size(shoes: Vec, shoe_size: u32) -> Vec { + shoes.into_iter().filter(|s| s.size == shoe_size).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn filters_by_size() { + let shoes = vec![ + Shoe { + size: 10, + style: String::from("sneaker"), + }, + Shoe { + size: 13, + style: String::from("sandal"), + }, + Shoe { + size: 10, + style: String::from("boot"), + }, + ]; + + let in_my_size = shoes_in_my_size(shoes, 10); + + assert_eq!( + in_my_size, + vec![ + Shoe { + size: 10, + style: String::from("sneaker") + }, + Shoe { + size: 10, + style: String::from("boot") + }, + ] + ); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-20/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-20/src/lib.rs new file mode 100644 index 0000000000..897804c429 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-20/src/lib.rs @@ -0,0 +1,11 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-21/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-21/src/lib.rs new file mode 100644 index 0000000000..97806be488 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-21/src/lib.rs @@ -0,0 +1,26 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +// ANCHOR: here +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + if self.count < 5 { + self.count += 1; + Some(self.count) + } else { + None + } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-22/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-22/src/lib.rs new file mode 100644 index 0000000000..f8faaca070 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-22/src/lib.rs @@ -0,0 +1,43 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + if self.count < 5 { + self.count += 1; + Some(self.count) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ANCHOR: here + #[test] + fn calling_next_directly() { + let mut counter = Counter::new(); + + assert_eq!(counter.next(), Some(1)); + assert_eq!(counter.next(), Some(2)); + assert_eq!(counter.next(), Some(3)); + assert_eq!(counter.next(), Some(4)); + assert_eq!(counter.next(), Some(5)); + assert_eq!(counter.next(), None); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-23/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-23/src/lib.rs new file mode 100644 index 0000000000..351321ff97 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-23/src/lib.rs @@ -0,0 +1,53 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + if self.count < 5 { + self.count += 1; + Some(self.count) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn calling_next_directly() { + let mut counter = Counter::new(); + + assert_eq!(counter.next(), Some(1)); + assert_eq!(counter.next(), Some(2)); + assert_eq!(counter.next(), Some(3)); + assert_eq!(counter.next(), Some(4)); + assert_eq!(counter.next(), Some(5)); + assert_eq!(counter.next(), None); + } + + // ANCHOR: here + #[test] + fn using_other_iterator_trait_methods() { + let sum: u32 = Counter::new() + .zip(Counter::new().skip(1)) + .map(|(a, b)| a * b) + .filter(|x| x % 3 == 0) + .sum(); + assert_eq!(18, sum); + } + // ANCHOR_END: here +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-25/poem.txt b/src/doc/book/listings/ch13-functional-features/listing-13-25/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-25/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-25/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-25/src/lib.rs new file mode 100644 index 0000000000..fe1dccf4ee --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-25/src/lib.rs @@ -0,0 +1,104 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(args: &[String]) -> Result { + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-25/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-25/src/main.rs new file mode 100644 index 0000000000..d09966e416 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-25/src/main.rs @@ -0,0 +1,23 @@ +use std::env; +use std::process; + +use minigrep::Config; + +// ANCHOR: here +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + // --snip-- + // ANCHOR_END: here + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-26/poem.txt b/src/doc/book/listings/ch13-functional-features/listing-13-26/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-26/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-26/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-26/src/lib.rs new file mode 100644 index 0000000000..44f0c7ee21 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-26/src/lib.rs @@ -0,0 +1,107 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: here +impl Config { + pub fn new(mut args: std::env::Args) -> Result { + // --snip-- + // ANCHOR_END: here + if args.len() < 3 { + return Err("not enough arguments"); + } + + let query = args[1].clone(); + let filename = args[2].clone(); + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-26/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-26/src/main.rs new file mode 100644 index 0000000000..06aac30e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-26/src/main.rs @@ -0,0 +1,17 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-27/poem.txt b/src/doc/book/listings/ch13-functional-features/listing-13-27/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-27/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-27/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-27/src/lib.rs new file mode 100644 index 0000000000..a4c58d9bdd --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-27/src/lib.rs @@ -0,0 +1,113 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +// ANCHOR: here +impl Config { + pub fn new(mut args: std::env::Args) -> Result { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; + + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a file name"), + }; + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} +// ANCHOR_END: here + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + let mut results = Vec::new(); + + for line in contents.lines() { + if line.contains(query) { + results.push(line); + } + } + + results +} + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-27/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-27/src/main.rs new file mode 100644 index 0000000000..06aac30e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-27/src/main.rs @@ -0,0 +1,17 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.lock b/src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.lock new file mode 100644 index 0000000000..88bf82d167 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.toml b/src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.toml new file mode 100644 index 0000000000..82606426f1 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-29/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-29/poem.txt b/src/doc/book/listings/ch13-functional-features/listing-13-29/poem.txt new file mode 100644 index 0000000000..8707527313 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-29/poem.txt @@ -0,0 +1,9 @@ +I'm nobody! Who are you? +Are you nobody, too? +Then there's a pair of us - don't tell! +They'd banish us, you know. + +How dreary to be somebody! +How public, like a frog +To tell your name the livelong day +To an admiring bog! diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-29/src/lib.rs b/src/doc/book/listings/ch13-functional-features/listing-13-29/src/lib.rs new file mode 100644 index 0000000000..bc8a77ef6e --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-29/src/lib.rs @@ -0,0 +1,106 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + pub fn new(mut args: std::env::Args) -> Result { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; + + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a file name"), + }; + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { + query, + filename, + case_sensitive, + }) + } +} + +pub fn run(config: Config) -> Result<(), Box> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +// ANCHOR: here +pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + contents + .lines() + .filter(|line| line.contains(query)) + .collect() +} +// ANCHOR_END: here + +pub fn search_case_insensitive<'a>( + query: &str, + contents: &'a str, +) -> Vec<&'a str> { + let query = query.to_lowercase(); + let mut results = Vec::new(); + + for line in contents.lines() { + if line.to_lowercase().contains(&query) { + results.push(line); + } + } + + results +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/listing-13-29/src/main.rs b/src/doc/book/listings/ch13-functional-features/listing-13-29/src/main.rs new file mode 100644 index 0000000000..06aac30e73 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/listing-13-29/src/main.rs @@ -0,0 +1,17 @@ +use std::env; +use std::process; + +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + + process::exit(1); + } +} diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock new file mode 100644 index 0000000000..e090432bc9 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cacher" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml new file mode 100644 index 0000000000..54ab6f2173 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cacher" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt new file mode 100644 index 0000000000..378a614d4e --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt @@ -0,0 +1,23 @@ +$ cargo test + Compiling cacher v0.1.0 (file:///projects/cacher) + Finished test [unoptimized + debuginfo] target(s) in 0.72s + Running target/debug/deps/cacher-4116485fb32b3fff + +running 1 test +test tests::call_with_different_values ... FAILED + +failures: + +---- tests::call_with_different_values stdout ---- +thread 'main' panicked at 'assertion failed: `(left == right)` + left: `1`, + right: `2`', src/lib.rs:43:9 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::call_with_different_values + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs new file mode 100644 index 0000000000..e7d677d0e3 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs @@ -0,0 +1,47 @@ +struct Cacher +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + Cacher { + calculation, + value: None, + } + } + + fn value(&mut self, arg: u32) -> u32 { + match self.value { + Some(v) => v, + None => { + let v = (self.calculation)(arg); + self.value = Some(v); + v + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ANCHOR: here + #[test] + fn call_with_different_values() { + let mut c = Cacher::new(|a| a); + + let v1 = c.value(1); + let v2 = c.value(2); + + assert_eq!(v2, 2); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock new file mode 100644 index 0000000000..a96532addb --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "equal-to-x" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml new file mode 100644 index 0000000000..4fd5d85234 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "equal-to-x" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt new file mode 100644 index 0000000000..a8d9e16d38 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling equal-to-x v0.1.0 (file:///projects/equal-to-x) +error[E0434]: can't capture dynamic environment in a fn item + --> src/main.rs:5:14 + | +5 | z == x + | ^ + | + = help: use the `|| { ... }` closure form instead + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0434`. +error: could not compile `equal-to-x`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs new file mode 100644 index 0000000000..1b5d2b930b --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let x = 4; + + fn equal_to_x(z: i32) -> bool { + z == x + } + + let y = 4; + + assert!(equal_to_x(y)); +} diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock new file mode 100644 index 0000000000..a96532addb --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "equal-to-x" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml new file mode 100644 index 0000000000..4fd5d85234 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "equal-to-x" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/output.txt b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/output.txt new file mode 100644 index 0000000000..43490332ed --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/output.txt @@ -0,0 +1,22 @@ +$ cargo run + Compiling equal-to-x v0.1.0 (file:///projects/equal-to-x) +error[E0382]: borrow of moved value: `x` + --> src/main.rs:6:40 + | +2 | let x = vec![1, 2, 3]; + | - move occurs because `x` has type `std::vec::Vec`, which does not implement the `Copy` trait +3 | +4 | let equal_to_x = move |z| z == x; + | -------- - variable moved due to use in closure + | | + | value moved into closure here +5 | +6 | println!("can't use x here: {:?}", x); + | ^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `equal-to-x`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs new file mode 100644 index 0000000000..19d4776088 --- /dev/null +++ b/src/doc/book/listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + let x = vec![1, 2, 3]; + + let equal_to_x = move |z| z == x; + + println!("can't use x here: {:?}", x); + + let y = vec![1, 2, 3]; + + assert!(equal_to_x(y)); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock new file mode 100644 index 0000000000..b304dd7c75 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "my_crate" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml new file mode 100644 index 0000000000..716953ae12 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "my_crate" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs new file mode 100644 index 0000000000..ed7abb7277 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-01/src/lib.rs @@ -0,0 +1,13 @@ +/// Adds one to the number given. +/// +/// # Examples +/// +/// ``` +/// let arg = 5; +/// let answer = my_crate::add_one(arg); +/// +/// assert_eq!(6, answer); +/// ``` +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock new file mode 100644 index 0000000000..b304dd7c75 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "my_crate" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml new file mode 100644 index 0000000000..716953ae12 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "my_crate" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs new file mode 100644 index 0000000000..64c9c439cc --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-02/src/lib.rs @@ -0,0 +1,21 @@ +// ANCHOR: here +//! # My Crate +//! +//! `my_crate` is a collection of utilities to make performing certain +//! calculations more convenient. + +/// Adds one to the number given. +// --snip-- +// ANCHOR_END: here +/// +/// # Examples +/// +/// ``` +/// let arg = 5; +/// let answer = my_crate::add_one(arg); +/// +/// assert_eq!(6, answer); +/// ``` +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs new file mode 100644 index 0000000000..00a81c5082 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-03/src/lib.rs @@ -0,0 +1,36 @@ +// ANCHOR: here +//! # Art +//! +//! A library for modeling artistic concepts. + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + // --snip-- + // ANCHOR_END: here + SecondaryColor::Orange + // ANCHOR: here + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs new file mode 100644 index 0000000000..b077a9a71a --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/lib.rs @@ -0,0 +1,29 @@ +//! # Art +//! +//! A library for modeling artistic concepts. + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Orange + } +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/main.rs new file mode 100644 index 0000000000..b1a4bf7922 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-04/src/main.rs @@ -0,0 +1,8 @@ +use art::kinds::PrimaryColor; +use art::utils::mix; + +fn main() { + let red = PrimaryColor::Red; + let yellow = PrimaryColor::Yellow; + mix(red, yellow); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs new file mode 100644 index 0000000000..c5aa9e7b00 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-05/src/lib.rs @@ -0,0 +1,41 @@ +// ANCHOR: here +//! # Art +//! +//! A library for modeling artistic concepts. + +pub use self::kinds::PrimaryColor; +pub use self::kinds::SecondaryColor; +pub use self::utils::mix; + +pub mod kinds { + // --snip-- + // ANCHOR_END: here + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } + // ANCHOR: here +} + +pub mod utils { + // --snip-- + // ANCHOR_END: here + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Orange + } + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock new file mode 100644 index 0000000000..df19c247b7 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "art" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml new file mode 100644 index 0000000000..a2e9e369bc --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "art" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs new file mode 100644 index 0000000000..daabd006df --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/lib.rs @@ -0,0 +1,33 @@ +//! # Art +//! +//! A library for modeling artistic concepts. + +pub use self::kinds::PrimaryColor; +pub use self::kinds::SecondaryColor; +pub use self::utils::mix; + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary colors in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Orange + } +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/main.rs new file mode 100644 index 0000000000..51f3b761db --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-06/src/main.rs @@ -0,0 +1,13 @@ +// ANCHOR: here +use art::mix; +use art::PrimaryColor; + +fn main() { + // --snip-- + // ANCHOR_END: here + let red = PrimaryColor::Red; + let yellow = PrimaryColor::Yellow; + mix(red, yellow); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml new file mode 100644 index 0000000000..8260fb541b --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs new file mode 100644 index 0000000000..b0bb869432 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/add-one/src/lib.rs @@ -0,0 +1,3 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs new file mode 100644 index 0000000000..7deb7962f4 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs @@ -0,0 +1,10 @@ +use add_one; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock new file mode 100644 index 0000000000..d37189b337 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml new file mode 100644 index 0000000000..c5ea8e510b --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] + +members = [ + "adder", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml new file mode 100644 index 0000000000..0e3940cf1a --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/adder/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml new file mode 100644 index 0000000000..8260fb541b --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs new file mode 100644 index 0000000000..b0bb869432 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs @@ -0,0 +1,3 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock new file mode 100644 index 0000000000..f17f35e860 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.lock @@ -0,0 +1,94 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)" = "c6785aa7dd976f5fbf3b71cfd9cd49d7f783c1ff565a858d71031c6c313aa5c6" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml new file mode 100644 index 0000000000..5b52051a63 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs new file mode 100644 index 0000000000..7b61b40a40 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/src/lib.rs @@ -0,0 +1,5 @@ +use rand; + +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs new file mode 100644 index 0000000000..7deb7962f4 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/adder/src/main.rs @@ -0,0 +1,10 @@ +use add_one; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml new file mode 100644 index 0000000000..8260fb541b --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs new file mode 100644 index 0000000000..40ceb12859 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs @@ -0,0 +1,13 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + assert_eq!(3, add_one(2)); + } +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs new file mode 100644 index 0000000000..7deb7962f4 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/adder/src/main.rs @@ -0,0 +1,10 @@ +use add_one; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml new file mode 100644 index 0000000000..c5ea8e510b --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] + +members = [ + "adder", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore b/src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore new file mode 100644 index 0000000000..958e568374 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-01-adder-crate/add/rustfmt-ignore @@ -0,0 +1,2 @@ +This listing is used for demonstrating how to set up a workspace, but the workspace isn't +completely set up yet, so rustfmt complains the crate mentioned in Cargo.toml doesn't exist yet. diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock new file mode 100644 index 0000000000..77292f6149 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/Cargo.toml new file mode 100644 index 0000000000..602f686d34 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/src/lib.rs new file mode 100644 index 0000000000..31e1bb209f --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/add-one/src/lib.rs @@ -0,0 +1,7 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-02-add-one/add/adder/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock new file mode 100644 index 0000000000..f17f35e860 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.lock @@ -0,0 +1,94 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "add-one" +version = "0.1.0" +dependencies = [ + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)" = "c6785aa7dd976f5fbf3b71cfd9cd49d7f783c1ff565a858d71031c6c313aa5c6" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml new file mode 100644 index 0000000000..d26e7cfb4d --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "adder", + "add-one", +] diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml new file mode 100644 index 0000000000..5b52051a63 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +rand = "0.5.5" diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs new file mode 100644 index 0000000000..7b61b40a40 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/add-one/src/lib.rs @@ -0,0 +1,5 @@ +use rand; + +pub fn add_one(x: i32) -> i32 { + x + 1 +} diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml new file mode 100644 index 0000000000..e73f1becaf --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] + +add-one = { path = "../add-one" } diff --git a/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs new file mode 100644 index 0000000000..eb4050dc36 --- /dev/null +++ b/src/doc/book/listings/ch14-more-about-cargo/output-only-03-use-rand/add/adder/src/main.rs @@ -0,0 +1,11 @@ +use add_one; +use rand; + +fn main() { + let num = 10; + println!( + "Hello, world! {} plus one is {}!", + num, + add_one::add_one(num) + ); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.lock new file mode 100644 index 0000000000..8c125fc84b --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "box-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.toml new file mode 100644 index 0000000000..4a0bb9d2f9 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "box-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-01/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-01/src/main.rs new file mode 100644 index 0000000000..8da1d905d6 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-01/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let b = Box::new(5); + println!("b = {}", b); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-02/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-02/src/main.rs new file mode 100644 index 0000000000..84640b9b90 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-02/src/main.rs @@ -0,0 +1,8 @@ +// ANCHOR: here +enum List { + Cons(i32, List), + Nil, +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt new file mode 100644 index 0000000000..f15aaacb9a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/output.txt @@ -0,0 +1,28 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) +error[E0072]: recursive type `List` has infinite size + --> src/main.rs:1:1 + | +1 | enum List { + | ^^^^^^^^^ recursive type has infinite size +2 | Cons(i32, List), + | ---- recursive without indirection + | + = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable + +error[E0391]: cycle detected when processing `List` + --> src/main.rs:1:1 + | +1 | enum List { + | ^^^^^^^^^ + | + = note: ...which again requires processing `List`, completing the cycle + = note: cycle used when computing dropck types for `Canonical { max_universe: U0, variables: [], value: ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, def_id: None }, value: List } }` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0072, E0391. +For more information about an error, try `rustc --explain E0072`. +error: could not compile `cons-list`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-03/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/src/main.rs new file mode 100644 index 0000000000..a96f3d7b18 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-03/src/main.rs @@ -0,0 +1,12 @@ +enum List { + Cons(i32, List), + Nil, +} + +// ANCHOR: here +use crate::List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Cons(2, Cons(3, Nil))); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-05/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-05/src/main.rs new file mode 100644 index 0000000000..22f7d8338a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-05/src/main.rs @@ -0,0 +1,10 @@ +enum List { + Cons(i32, Box), + Nil, +} + +use crate::List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-06/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-06/src/main.rs new file mode 100644 index 0000000000..174b620cf4 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-06/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let x = 5; + let y = &x; + + assert_eq!(5, x); + assert_eq!(5, *y); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-07/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-07/src/main.rs new file mode 100644 index 0000000000..4933a416ba --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-07/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let x = 5; + let y = Box::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-08/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-08/src/main.rs new file mode 100644 index 0000000000..f485946731 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-08/src/main.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-09/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/output.txt new file mode 100644 index 0000000000..8fbd56124b --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling deref-example v0.1.0 (file:///projects/deref-example) +error[E0614]: type `MyBox<{integer}>` cannot be dereferenced + --> src/main.rs:14:19 + | +14 | assert_eq!(5, *y); + | ^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0614`. +error: could not compile `deref-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-09/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/src/main.rs new file mode 100644 index 0000000000..d07f2d78a0 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-09/src/main.rs @@ -0,0 +1,17 @@ +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +// ANCHOR: here +fn main() { + let x = 5; + let y = MyBox::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-10/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-10/src/main.rs new file mode 100644 index 0000000000..a97f97c9b7 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-10/src/main.rs @@ -0,0 +1,27 @@ +// ANCHOR: here +use std::ops::Deref; + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} +// ANCHOR_END: here + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +fn main() { + let x = 5; + let y = MyBox::new(x); + + assert_eq!(5, x); + assert_eq!(5, *y); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-11/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-11/src/main.rs new file mode 100644 index 0000000000..b73ad89c25 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-11/src/main.rs @@ -0,0 +1,7 @@ +// ANCHOR: here +fn hello(name: &str) { + println!("Hello, {}!", name); +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-12/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-12/src/main.rs new file mode 100644 index 0000000000..6a3e143cc3 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-12/src/main.rs @@ -0,0 +1,28 @@ +use std::ops::Deref; + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +fn hello(name: &str) { + println!("Hello, {}!", name); +} + +// ANCHOR: here +fn main() { + let m = MyBox::new(String::from("Rust")); + hello(&m); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-13/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-13/src/main.rs new file mode 100644 index 0000000000..ef5361c120 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-13/src/main.rs @@ -0,0 +1,28 @@ +use std::ops::Deref; + +impl Deref for MyBox { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +struct MyBox(T); + +impl MyBox { + fn new(x: T) -> MyBox { + MyBox(x) + } +} + +fn hello(name: &str) { + println!("Hello, {}!", name); +} + +// ANCHOR: here +fn main() { + let m = MyBox::new(String::from("Rust")); + hello(&(*m)[..]); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.lock new file mode 100644 index 0000000000..eb8a2817ac --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "drop-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.toml new file mode 100644 index 0000000000..e9ad457cf2 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "drop-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-14/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/output.txt new file mode 100644 index 0000000000..4e795949a0 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling drop-example v0.1.0 (file:///projects/drop-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.60s + Running `target/debug/drop-example` +CustomSmartPointers created. +Dropping CustomSmartPointer with data `other stuff`! +Dropping CustomSmartPointer with data `my stuff`! diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-14/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/src/main.rs new file mode 100644 index 0000000000..231612ae62 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-14/src/main.rs @@ -0,0 +1,19 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropping CustomSmartPointer with data `{}`!", self.data); + } +} + +fn main() { + let c = CustomSmartPointer { + data: String::from("my stuff"), + }; + let d = CustomSmartPointer { + data: String::from("other stuff"), + }; + println!("CustomSmartPointers created."); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.lock new file mode 100644 index 0000000000..eb8a2817ac --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "drop-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.toml new file mode 100644 index 0000000000..e9ad457cf2 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "drop-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-15/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/output.txt new file mode 100644 index 0000000000..4af05876e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/output.txt @@ -0,0 +1,14 @@ +$ cargo run + Compiling drop-example v0.1.0 (file:///projects/drop-example) +error[E0040]: explicit use of destructor method + --> src/main.rs:16:7 + | +16 | c.drop(); + | ^^^^ explicit destructor calls not allowed + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0040`. +error: could not compile `drop-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-15/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/src/main.rs new file mode 100644 index 0000000000..ff3b391a91 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-15/src/main.rs @@ -0,0 +1,20 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropping CustomSmartPointer with data `{}`!", self.data); + } +} + +// ANCHOR: here +fn main() { + let c = CustomSmartPointer { + data: String::from("some data"), + }; + println!("CustomSmartPointer created."); + c.drop(); + println!("CustomSmartPointer dropped before the end of main."); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.lock new file mode 100644 index 0000000000..eb8a2817ac --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "drop-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.toml new file mode 100644 index 0000000000..e9ad457cf2 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "drop-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-16/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/output.txt new file mode 100644 index 0000000000..e960cd89a2 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling drop-example v0.1.0 (file:///projects/drop-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.73s + Running `target/debug/drop-example` +CustomSmartPointer created. +Dropping CustomSmartPointer with data `some data`! +CustomSmartPointer dropped before the end of main. diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-16/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/src/main.rs new file mode 100644 index 0000000000..f11715c45e --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-16/src/main.rs @@ -0,0 +1,20 @@ +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropping CustomSmartPointer with data `{}`!", self.data); + } +} + +// ANCHOR: here +fn main() { + let c = CustomSmartPointer { + data: String::from("some data"), + }; + println!("CustomSmartPointer created."); + drop(c); + println!("CustomSmartPointer dropped before the end of main."); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-17/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/output.txt new file mode 100644 index 0000000000..5966a71ec2 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) +error[E0382]: use of moved value: `a` + --> src/main.rs:11:30 + | +9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); + | - move occurs because `a` has type `List`, which does not implement the `Copy` trait +10 | let b = Cons(3, Box::new(a)); + | - value moved here +11 | let c = Cons(4, Box::new(a)); + | ^ value used here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `cons-list`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-17/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/src/main.rs new file mode 100644 index 0000000000..47c33e4c46 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-17/src/main.rs @@ -0,0 +1,12 @@ +enum List { + Cons(i32, Box), + Nil, +} + +use crate::List::{Cons, Nil}; + +fn main() { + let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); + let b = Cons(3, Box::new(a)); + let c = Cons(4, Box::new(a)); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-18/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-18/src/main.rs new file mode 100644 index 0000000000..602f7de40d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-18/src/main.rs @@ -0,0 +1,13 @@ +enum List { + Cons(i32, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::rc::Rc; + +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + let b = Cons(3, Rc::clone(&a)); + let c = Cons(4, Rc::clone(&a)); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-19/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/output.txt new file mode 100644 index 0000000000..6a8cc8efe1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/output.txt @@ -0,0 +1,8 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) + Finished dev [unoptimized + debuginfo] target(s) in 0.45s + Running `target/debug/cons-list` +count after creating a = 1 +count after creating b = 2 +count after creating c = 3 +count after c goes out of scope = 2 diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-19/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/src/main.rs new file mode 100644 index 0000000000..1bd7bc533a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-19/src/main.rs @@ -0,0 +1,21 @@ +enum List { + Cons(i32, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::rc::Rc; + +// ANCHOR: here +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + println!("count after creating a = {}", Rc::strong_count(&a)); + let b = Cons(3, Rc::clone(&a)); + println!("count after creating b = {}", Rc::strong_count(&a)); + { + let c = Cons(4, Rc::clone(&a)); + println!("count after creating c = {}", Rc::strong_count(&a)); + } + println!("count after c goes out of scope = {}", Rc::strong_count(&a)); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-20/src/lib.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-20/src/lib.rs new file mode 100644 index 0000000000..d3a9003736 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-20/src/lib.rs @@ -0,0 +1,38 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-21/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/output.txt new file mode 100644 index 0000000000..851b5caf98 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/output.txt @@ -0,0 +1,16 @@ +$ cargo test + Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker) +error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&` reference + --> src/lib.rs:58:13 + | +57 | fn send(&self, message: &str) { + | ----- help: consider changing this to be a mutable reference: `&mut self` +58 | self.sent_messages.push(String::from(message)); + | ^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. +error: could not compile `limit-tracker`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-21/src/lib.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/src/lib.rs new file mode 100644 index 0000000000..9e403e3ca8 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-21/src/lib.rs @@ -0,0 +1,73 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + + struct MockMessenger { + sent_messages: Vec, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: vec![], + } + } + } + + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + self.sent_messages.push(String::from(message)); + } + } + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + + assert_eq!(mock_messenger.sent_messages.len(), 1); + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-22/src/lib.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-22/src/lib.rs new file mode 100644 index 0000000000..dc259f7fca --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-22/src/lib.rs @@ -0,0 +1,80 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +// ANCHOR: here +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + struct MockMessenger { + sent_messages: RefCell>, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: RefCell::new(vec![]), + } + } + } + + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + self.sent_messages.borrow_mut().push(String::from(message)); + } + } + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + // --snip-- + // ANCHOR_END: here + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + // ANCHOR: here + + // ANCHOR: here + assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.lock new file mode 100644 index 0000000000..4dc2226a57 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "limit-tracker" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.toml new file mode 100644 index 0000000000..b230a2326b --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "limit-tracker" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt new file mode 100644 index 0000000000..9d69d439c7 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/output.txt @@ -0,0 +1,21 @@ +$ cargo test + Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker) + Finished test [unoptimized + debuginfo] target(s) in 0.91s + Running target/debug/deps/limit_tracker-d1b2637139dca6ca + +running 1 test +test tests::it_sends_an_over_75_percent_warning_message ... FAILED + +failures: + +---- tests::it_sends_an_over_75_percent_warning_message stdout ---- +thread 'main' panicked at 'already borrowed: BorrowMutError', src/libcore/result.rs:1188:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. + + +failures: + tests::it_sends_an_over_75_percent_warning_message + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out + +error: test failed, to rerun pass '--lib' diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-23/src/lib.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/src/lib.rs new file mode 100644 index 0000000000..4e599ddc8c --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-23/src/lib.rs @@ -0,0 +1,78 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &T, max: usize) -> LimitTracker { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + struct MockMessenger { + sent_messages: RefCell>, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: RefCell::new(vec![]), + } + } + } + + // ANCHOR: here + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + let mut one_borrow = self.sent_messages.borrow_mut(); + let mut two_borrow = self.sent_messages.borrow_mut(); + + one_borrow.push(String::from(message)); + two_borrow.push(String::from(message)); + } + } + // ANCHOR_END: here + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + + assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); + } +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-24/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/output.txt new file mode 100644 index 0000000000..bfe217bf41 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) + Finished dev [unoptimized + debuginfo] target(s) in 0.63s + Running `target/debug/cons-list` +a after = Cons(RefCell { value: 15 }, Nil) +b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) +c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-24/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/src/main.rs new file mode 100644 index 0000000000..ac271fa21f --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-24/src/main.rs @@ -0,0 +1,24 @@ +#[derive(Debug)] +enum List { + Cons(Rc>, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::Rc; + +fn main() { + let value = Rc::new(RefCell::new(5)); + + let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); + + let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); + let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); + + *value.borrow_mut() += 10; + + println!("a after = {:?}", a); + println!("b after = {:?}", b); + println!("c after = {:?}", c); +} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-25/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-25/src/main.rs new file mode 100644 index 0000000000..f36c7fd06d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-25/src/main.rs @@ -0,0 +1,20 @@ +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Debug)] +enum List { + Cons(i32, RefCell>), + Nil, +} + +impl List { + fn tail(&self) -> Option<&RefCell>> { + match self { + Cons(_, item) => Some(item), + Nil => None, + } + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.lock new file mode 100644 index 0000000000..a792c49aaf --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "cons-list" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.toml new file mode 100644 index 0000000000..86c8e956e1 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "cons-list" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-26/output.txt b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/output.txt new file mode 100644 index 0000000000..8b8eb40b60 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/output.txt @@ -0,0 +1,11 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) + Finished dev [unoptimized + debuginfo] target(s) in 0.53s + Running `target/debug/cons-list` +a initial rc count = 1 +a next item = Some(RefCell { value: Nil }) +a rc count after b creation = 2 +b initial rc count = 1 +b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) }) +b rc count after changing a = 2 +a rc count after changing a = 2 diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-26/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/src/main.rs new file mode 100644 index 0000000000..08963aaa51 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-26/src/main.rs @@ -0,0 +1,44 @@ +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Debug)] +enum List { + Cons(i32, RefCell>), + Nil, +} + +impl List { + fn tail(&self) -> Option<&RefCell>> { + match self { + Cons(_, item) => Some(item), + Nil => None, + } + } +} + +// ANCHOR: here +fn main() { + let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); + + println!("a initial rc count = {}", Rc::strong_count(&a)); + println!("a next item = {:?}", a.tail()); + + let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); + + println!("a rc count after b creation = {}", Rc::strong_count(&a)); + println!("b initial rc count = {}", Rc::strong_count(&b)); + println!("b next item = {:?}", b.tail()); + + if let Some(link) = a.tail() { + *link.borrow_mut() = Rc::clone(&b); + } + + println!("b rc count after changing a = {}", Rc::strong_count(&b)); + println!("a rc count after changing a = {}", Rc::strong_count(&a)); + + // Uncomment the next line to see that we have a cycle; + // it will overflow the stack + // println!("a next item = {:?}", a.tail()); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.lock new file mode 100644 index 0000000000..dd1f00a874 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tree" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.toml new file mode 100644 index 0000000000..d6774b817a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tree" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-27/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-27/src/main.rs new file mode 100644 index 0000000000..335d154ddb --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-27/src/main.rs @@ -0,0 +1,24 @@ +// ANCHOR: here +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Debug)] +struct Node { + value: i32, + children: RefCell>>, +} +// ANCHOR_END: here + +// ANCHOR: there +fn main() { + let leaf = Rc::new(Node { + value: 3, + children: RefCell::new(vec![]), + }); + + let branch = Rc::new(Node { + value: 5, + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); +} +// ANCHOR_END: there diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.lock new file mode 100644 index 0000000000..dd1f00a874 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tree" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.toml new file mode 100644 index 0000000000..d6774b817a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-28/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tree" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-28/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-28/src/main.rs new file mode 100644 index 0000000000..fabd1cbceb --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-28/src/main.rs @@ -0,0 +1,33 @@ +// ANCHOR: here +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} +// ANCHOR_END: here + +// ANCHOR: there +fn main() { + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); +} +// ANCHOR_END: there diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.lock new file mode 100644 index 0000000000..dd1f00a874 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "tree" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.toml new file mode 100644 index 0000000000..d6774b817a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-29/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tree" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/listing-15-29/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/listing-15-29/src/main.rs new file mode 100644 index 0000000000..ea13df0eb4 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/listing-15-29/src/main.rs @@ -0,0 +1,54 @@ +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} + +// ANCHOR: here +fn main() { + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + + { + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!( + "branch strong = {}, weak = {}", + Rc::strong_count(&branch), + Rc::weak_count(&branch), + ); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + } + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock new file mode 100644 index 0000000000..340f6604a2 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "borrowing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml new file mode 100644 index 0000000000..1558eb615e --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "borrowing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt new file mode 100644 index 0000000000..c8e5592de7 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling borrowing v0.1.0 (file:///projects/borrowing) +error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable + --> src/main.rs:3:13 + | +2 | let x = 5; + | - help: consider changing this to be mutable: `mut x` +3 | let y = &mut x; + | ^^^^^^ cannot borrow as mutable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0596`. +error: could not compile `borrowing`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs new file mode 100644 index 0000000000..8f48d41c15 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let x = 5; + let y = &mut x; +} diff --git a/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock new file mode 100644 index 0000000000..4297c6733d --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "deref-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml new file mode 100644 index 0000000000..2a9630fe4a --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "deref-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt new file mode 100644 index 0000000000..4368ee65f6 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling deref-example v0.1.0 (file:///projects/deref-example) +error[E0277]: can't compare `{integer}` with `&{integer}` + --> src/main.rs:6:5 + | +6 | assert_eq!(5, y); + | ^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}` + | + = help: the trait `std::cmp::PartialEq<&{integer}>` is not implemented for `{integer}` + = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `deref-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs new file mode 100644 index 0000000000..4e20cae0b8 --- /dev/null +++ b/src/doc/book/listings/ch15-smart-pointers/output-only-01-comparing-to-reference/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + let x = 5; + let y = &x; + + assert_eq!(5, x); + assert_eq!(5, y); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs new file mode 100644 index 0000000000..6305a98e3d --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-01/src/main.rs @@ -0,0 +1,16 @@ +use std::thread; +use std::time::Duration; + +fn main() { + thread::spawn(|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + thread::sleep(Duration::from_millis(1)); + } + }); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs new file mode 100644 index 0000000000..e37607f1d6 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-02/src/main.rs @@ -0,0 +1,18 @@ +use std::thread; +use std::time::Duration; + +fn main() { + let handle = thread::spawn(|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + thread::sleep(Duration::from_millis(1)); + } + }); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } + + handle.join().unwrap(); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/output.txt new file mode 100644 index 0000000000..1dd4deeb2e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/output.txt @@ -0,0 +1,29 @@ +$ cargo run + Compiling threads v0.1.0 (file:///projects/threads) +error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function + --> src/main.rs:6:32 + | +6 | let handle = thread::spawn(|| { + | ^^ may outlive borrowed value `v` +7 | println!("Here's a vector: {:?}", v); + | - `v` is borrowed here + | +note: function requires argument type to outlive `'static` + --> src/main.rs:6:18 + | +6 | let handle = thread::spawn(|| { + | __________________^ +7 | | println!("Here's a vector: {:?}", v); +8 | | }); + | |______^ +help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword + | +6 | let handle = thread::spawn(move || { + | ^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0373`. +error: could not compile `threads`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs new file mode 100644 index 0000000000..defc876482 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-03/src/main.rs @@ -0,0 +1,11 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(|| { + println!("Here's a vector: {:?}", v); + }); + + handle.join().unwrap(); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs new file mode 100644 index 0000000000..0bccc5f56f --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-04/src/main.rs @@ -0,0 +1,13 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(|| { + println!("Here's a vector: {:?}", v); + }); + + drop(v); // oh no! + + handle.join().unwrap(); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs new file mode 100644 index 0000000000..a6547dc4c1 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-05/src/main.rs @@ -0,0 +1,11 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(move || { + println!("Here's a vector: {:?}", v); + }); + + handle.join().unwrap(); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs new file mode 100644 index 0000000000..d80dac4a0a --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-06/src/main.rs @@ -0,0 +1,5 @@ +use std::sync::mpsc; + +fn main() { + let (tx, rx) = mpsc::channel(); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs new file mode 100644 index 0000000000..7859b64dae --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-07/src/main.rs @@ -0,0 +1,11 @@ +use std::sync::mpsc; +use std::thread; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + }); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs new file mode 100644 index 0000000000..fbba9167d4 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-08/src/main.rs @@ -0,0 +1,14 @@ +use std::sync::mpsc; +use std::thread; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + }); + + let received = rx.recv().unwrap(); + println!("Got: {}", received); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt new file mode 100644 index 0000000000..11bfc6fe32 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/output.txt @@ -0,0 +1,18 @@ +$ cargo run + Compiling message-passing v0.1.0 (file:///projects/message-passing) +error[E0382]: borrow of moved value: `val` + --> src/main.rs:10:31 + | +8 | let val = String::from("hi"); + | --- move occurs because `val` has type `std::string::String`, which does not implement the `Copy` trait +9 | tx.send(val).unwrap(); + | --- value moved here +10 | println!("val is {}", val); + | ^^^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `message-passing`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs new file mode 100644 index 0000000000..98a8129ab3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-09/src/main.rs @@ -0,0 +1,15 @@ +use std::sync::mpsc; +use std::thread; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + println!("val is {}", val); + }); + + let received = rx.recv().unwrap(); + println!("Got: {}", received); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs new file mode 100644 index 0000000000..82b220de45 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-10/src/main.rs @@ -0,0 +1,25 @@ +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +fn main() { + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + for received in rx { + println!("Got: {}", received); + } +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock new file mode 100644 index 0000000000..55d2252da5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "message-passing" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml new file mode 100644 index 0000000000..8fd8808ea5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "message-passing" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs new file mode 100644 index 0000000000..f0acf4c2d2 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-11/src/main.rs @@ -0,0 +1,46 @@ +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +fn main() { + // ANCHOR: here + // --snip-- + + let (tx, rx) = mpsc::channel(); + + let tx1 = mpsc::Sender::clone(&tx); + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx1.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + thread::spawn(move || { + let vals = vec![ + String::from("more"), + String::from("messages"), + String::from("for"), + String::from("you"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + for received in rx { + println!("Got: {}", received); + } + + // --snip-- + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs new file mode 100644 index 0000000000..0c0d6767ad --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-12/src/main.rs @@ -0,0 +1,12 @@ +use std::sync::Mutex; + +fn main() { + let m = Mutex::new(5); + + { + let mut num = m.lock().unwrap(); + *num = 6; + } + + println!("m = {:?}", m); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/output.txt new file mode 100644 index 0000000000..7369ec41b5 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling shared-state v0.1.0 (file:///projects/shared-state) +error[E0382]: use of moved value: `counter` + --> src/main.rs:9:36 + | +5 | let counter = Mutex::new(0); + | ------- move occurs because `counter` has type `std::sync::Mutex`, which does not implement the `Copy` trait +... +9 | let handle = thread::spawn(move || { + | ^^^^^^^ value moved into closure here, in previous iteration of loop +10 | let mut num = counter.lock().unwrap(); + | ------- use occurs due to use in closure + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `shared-state`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs new file mode 100644 index 0000000000..4e380a59ac --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-13/src/main.rs @@ -0,0 +1,22 @@ +use std::sync::Mutex; +use std::thread; + +fn main() { + let counter = Mutex::new(0); + let mut handles = vec![]; + + for _ in 0..10 { + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt new file mode 100644 index 0000000000..200c55e220 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling shared-state v0.1.0 (file:///projects/shared-state) +error[E0277]: `std::rc::Rc>` cannot be sent between threads safely + --> src/main.rs:11:22 + | +11 | let handle = thread::spawn(move || { + | ^^^^^^^^^^^^^ `std::rc::Rc>` cannot be sent between threads safely + | + = help: within `[closure@src/main.rs:11:36: 15:10 counter:std::rc::Rc>]`, the trait `std::marker::Send` is not implemented for `std::rc::Rc>` + = note: required because it appears within the type `[closure@src/main.rs:11:36: 15:10 counter:std::rc::Rc>]` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `shared-state`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs new file mode 100644 index 0000000000..d940b1a344 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-14/src/main.rs @@ -0,0 +1,24 @@ +use std::rc::Rc; +use std::sync::Mutex; +use std::thread; + +fn main() { + let counter = Rc::new(Mutex::new(0)); + let mut handles = vec![]; + + for _ in 0..10 { + let counter = Rc::clone(&counter); + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs new file mode 100644 index 0000000000..30247dd52f --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/listing-16-15/src/main.rs @@ -0,0 +1,23 @@ +use std::sync::{Arc, Mutex}; +use std::thread; + +fn main() { + let counter = Arc::new(Mutex::new(0)); + let mut handles = vec![]; + + for _ in 0..10 { + let counter = Arc::clone(&counter); + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs new file mode 100644 index 0000000000..6205e57d33 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs @@ -0,0 +1,18 @@ +use std::thread; +use std::time::Duration; + +fn main() { + let handle = thread::spawn(|| { + for i in 1..10 { + println!("hi number {} from the spawned thread!", i); + thread::sleep(Duration::from_millis(1)); + } + }); + + handle.join().unwrap(); + + for i in 1..5 { + println!("hi number {} from the main thread!", i); + thread::sleep(Duration::from_millis(1)); + } +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock new file mode 100644 index 0000000000..8e7ba9cf5d --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "shared-state" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml new file mode 100644 index 0000000000..e7c75ac918 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "shared-state" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs new file mode 100644 index 0000000000..dbb1397719 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/no-listing-02-no-loop-to-understand-error/src/main.rs @@ -0,0 +1,27 @@ +use std::sync::Mutex; +use std::thread; + +fn main() { + let counter = Mutex::new(0); + let mut handles = vec![]; + + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + + let handle2 = thread::spawn(move || { + let mut num2 = counter.lock().unwrap(); + + *num2 += 1; + }); + handles.push(handle2); + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock new file mode 100644 index 0000000000..8ecc3ae17e --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "threads" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml new file mode 100644 index 0000000000..68a31e10b3 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "threads" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt new file mode 100644 index 0000000000..2d1cb3c8b7 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt @@ -0,0 +1,22 @@ +$ cargo run + Compiling threads v0.1.0 (file:///projects/threads) +error[E0382]: use of moved value: `v` + --> src/main.rs:10:10 + | +4 | let v = vec![1, 2, 3]; + | - move occurs because `v` has type `std::vec::Vec`, which does not implement the `Copy` trait +5 | +6 | let handle = thread::spawn(move || { + | ------- value moved into closure here +7 | println!("Here's a vector: {:?}", v); + | - variable moved due to use in closure +... +10 | drop(v); // oh no! + | ^ value used here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `threads`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs new file mode 100644 index 0000000000..70f659c5f6 --- /dev/null +++ b/src/doc/book/listings/ch16-fearless-concurrency/output-only-01-move-drop/src/main.rs @@ -0,0 +1,13 @@ +use std::thread; + +fn main() { + let v = vec![1, 2, 3]; + + let handle = thread::spawn(move || { + println!("Here's a vector: {:?}", v); + }); + + drop(v); // oh no! + + handle.join().unwrap(); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-01/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-01/Cargo.lock new file mode 100644 index 0000000000..471d8dfc3c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "averaged-collection" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-01/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-01/Cargo.toml new file mode 100644 index 0000000000..ab96488d1e --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "averaged-collection" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-01/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-01/src/lib.rs new file mode 100644 index 0000000000..b5ce2ab642 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-01/src/lib.rs @@ -0,0 +1,4 @@ +pub struct AveragedCollection { + list: Vec, + average: f64, +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-02/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-02/Cargo.lock new file mode 100644 index 0000000000..471d8dfc3c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "averaged-collection" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-02/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-02/Cargo.toml new file mode 100644 index 0000000000..ab96488d1e --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "averaged-collection" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-02/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-02/src/lib.rs new file mode 100644 index 0000000000..bb407ec5fe --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-02/src/lib.rs @@ -0,0 +1,33 @@ +pub struct AveragedCollection { + list: Vec, + average: f64, +} + +// ANCHOR: here +impl AveragedCollection { + pub fn add(&mut self, value: i32) { + self.list.push(value); + self.update_average(); + } + + pub fn remove(&mut self) -> Option { + let result = self.list.pop(); + match result { + Some(value) => { + self.update_average(); + Some(value) + } + None => None, + } + } + + pub fn average(&self) -> f64 { + self.average + } + + fn update_average(&mut self) { + let total: i32 = self.list.iter().sum(); + self.average = total as f64 / self.list.len() as f64; + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-03/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-03/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-03/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-03/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-03/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-03/src/lib.rs new file mode 100644 index 0000000000..3a5cb779c4 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-03/src/lib.rs @@ -0,0 +1,3 @@ +pub trait Draw { + fn draw(&self); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-04/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-04/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-04/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-04/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-04/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-04/src/lib.rs new file mode 100644 index 0000000000..0c45e2a624 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-04/src/lib.rs @@ -0,0 +1,9 @@ +pub trait Draw { + fn draw(&self); +} + +// ANCHOR: here +pub struct Screen { + pub components: Vec>, +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-05/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-05/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-05/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-05/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-05/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-05/src/lib.rs new file mode 100644 index 0000000000..57ebb5782a --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-05/src/lib.rs @@ -0,0 +1,17 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +// ANCHOR: here +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-06/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-06/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-06/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-06/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-06/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-06/src/lib.rs new file mode 100644 index 0000000000..63a8907d36 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-06/src/lib.rs @@ -0,0 +1,20 @@ +pub trait Draw { + fn draw(&self); +} + +// ANCHOR: here +pub struct Screen { + pub components: Vec, +} + +impl Screen +where + T: Draw, +{ + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-07/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-07/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-07/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-07/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-07/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-07/src/lib.rs new file mode 100644 index 0000000000..413dc6ff16 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-07/src/lib.rs @@ -0,0 +1,31 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +// ANCHOR: here +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch17-oop/listing-17-08/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-08/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-08/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-08/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-08/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-08/src/lib.rs new file mode 100644 index 0000000000..960fee23da --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-08/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-08/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-08/src/main.rs new file mode 100644 index 0000000000..9575d407e3 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-08/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +use gui::Draw; + +struct SelectBox { + width: u32, + height: u32, + options: Vec, +} + +impl Draw for SelectBox { + fn draw(&self) { + // code to actually draw a select box + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch17-oop/listing-17-09/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-09/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-09/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-09/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-09/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-09/src/lib.rs new file mode 100644 index 0000000000..960fee23da --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-09/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-09/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-09/src/main.rs new file mode 100644 index 0000000000..4eb13f6b73 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-09/src/main.rs @@ -0,0 +1,40 @@ +use gui::Draw; + +struct SelectBox { + width: u32, + height: u32, + options: Vec, +} + +impl Draw for SelectBox { + fn draw(&self) { + // code to actually draw a select box + } +} + +// ANCHOR: here +use gui::{Button, Screen}; + +fn main() { + let screen = Screen { + components: vec![ + Box::new(SelectBox { + width: 75, + height: 10, + options: vec![ + String::from("Yes"), + String::from("Maybe"), + String::from("No"), + ], + }), + Box::new(Button { + width: 50, + height: 10, + label: String::from("OK"), + }), + ], + }; + + screen.run(); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-10/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-10/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-10/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-10/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-10/output.txt b/src/doc/book/listings/ch17-oop/listing-17-10/output.txt new file mode 100644 index 0000000000..b18e1e9b4e --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-10/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling gui v0.1.0 (file:///projects/gui) +error[E0277]: the trait bound `std::string::String: gui::Draw` is not satisfied + --> src/main.rs:5:26 + | +5 | components: vec![Box::new(String::from("Hi"))], + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `gui::Draw` is not implemented for `std::string::String` + | + = note: required for the cast to the object type `dyn gui::Draw` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `gui`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch17-oop/listing-17-10/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-10/src/lib.rs new file mode 100644 index 0000000000..960fee23da --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-10/src/lib.rs @@ -0,0 +1,27 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + // code to actually draw a button + } +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-10/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-10/src/main.rs new file mode 100644 index 0000000000..2ede87ab78 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-10/src/main.rs @@ -0,0 +1,9 @@ +use gui::Screen; + +fn main() { + let screen = Screen { + components: vec![Box::new(String::from("Hi"))], + }; + + screen.run(); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-11/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-11/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-11/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-11/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-11/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-11/src/main.rs new file mode 100644 index 0000000000..d99170a973 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-11/src/main.rs @@ -0,0 +1,20 @@ +// ANCHOR: all +use blog::Post; + +// ANCHOR: here +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + // ANCHOR_END: here + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); + // ANCHOR: here +} +// ANCHOR_END: here +// ANCHOR_END: all diff --git a/src/doc/book/listings/ch17-oop/listing-17-12/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-12/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-12/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-12/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-12/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-12/src/lib.rs new file mode 100644 index 0000000000..b8156c39de --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-12/src/lib.rs @@ -0,0 +1,19 @@ +pub struct Post { + state: Option>, + content: String, +} + +impl Post { + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } +} + +trait State {} + +struct Draft {} + +impl State for Draft {} diff --git a/src/doc/book/listings/ch17-oop/listing-17-12/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-12/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-12/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-13/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-13/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-13/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-13/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-13/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-13/src/lib.rs new file mode 100644 index 0000000000..0ae3fa6e81 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-13/src/lib.rs @@ -0,0 +1,30 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + // ANCHOR: here + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } +} +// ANCHOR_END: here + +trait State {} + +struct Draft {} + +impl State for Draft {} + +fn main() {} diff --git a/src/doc/book/listings/ch17-oop/listing-17-13/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-13/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-13/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-14/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-14/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-14/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-14/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-14/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-14/src/lib.rs new file mode 100644 index 0000000000..0d010f50c5 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-14/src/lib.rs @@ -0,0 +1,34 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + // ANCHOR: here + pub fn content(&self) -> &str { + "" + } +} +// ANCHOR_END: here + +trait State {} + +struct Draft {} + +impl State for Draft {} + +fn main() {} diff --git a/src/doc/book/listings/ch17-oop/listing-17-14/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-14/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-14/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-15/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-15/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-15/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-15/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-15/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-15/src/lib.rs new file mode 100644 index 0000000000..806b4e49db --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-15/src/lib.rs @@ -0,0 +1,54 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn content(&self) -> &str { + "" + } + + // ANCHOR: here + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } +} + +trait State { + fn request_review(self: Box) -> Box; +} + +struct Draft {} + +impl State for Draft { + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } +} + +struct PendingReview {} + +impl State for PendingReview { + fn request_review(self: Box) -> Box { + self + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch17-oop/listing-17-15/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-15/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-15/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-16/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-16/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-16/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-16/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-16/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-16/src/lib.rs new file mode 100644 index 0000000000..92cb298134 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-16/src/lib.rs @@ -0,0 +1,85 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn content(&self) -> &str { + "" + } + + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } + + // ANCHOR: here + pub fn approve(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.approve()) + } + } +} + +trait State { + fn request_review(self: Box) -> Box; + fn approve(self: Box) -> Box; +} + +struct Draft {} + +impl State for Draft { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } + + // ANCHOR: here + fn approve(self: Box) -> Box { + self + } +} + +struct PendingReview {} + +impl State for PendingReview { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box { + self + } + + // ANCHOR: here + fn approve(self: Box) -> Box { + Box::new(Published {}) + } +} + +struct Published {} + +impl State for Published { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + self + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-16/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-16/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-16/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-17/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-17/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-17/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-17/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-17/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-17/src/lib.rs new file mode 100644 index 0000000000..0beee7b8da --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-17/src/lib.rs @@ -0,0 +1,82 @@ +pub struct Post { + state: Option>, + content: String, +} + +// ANCHOR: here +impl Post { + // --snip-- + // ANCHOR_END: here + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + // ANCHOR: here + pub fn content(&self) -> &str { + self.state.as_ref().unwrap().content(self) + } + // --snip-- + // ANCHOR_END: here + + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } + + pub fn approve(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.approve()) + } + } + // ANCHOR: here +} +// ANCHOR_END: here + +trait State { + fn request_review(self: Box) -> Box; + fn approve(self: Box) -> Box; +} + +struct Draft {} + +impl State for Draft { + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } + + fn approve(self: Box) -> Box { + self + } +} + +struct PendingReview {} + +impl State for PendingReview { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + Box::new(Published {}) + } +} + +struct Published {} + +impl State for Published { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + self + } +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-17/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-17/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-17/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-18/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-18/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-18/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-18/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-18/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-18/src/lib.rs new file mode 100644 index 0000000000..1bac8a87aa --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-18/src/lib.rs @@ -0,0 +1,94 @@ +pub struct Post { + state: Option>, + content: String, +} + +impl Post { + pub fn new() -> Post { + Post { + state: Some(Box::new(Draft {})), + content: String::new(), + } + } + + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn content(&self) -> &str { + self.state.as_ref().unwrap().content(self) + } + + pub fn request_review(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.request_review()) + } + } + + pub fn approve(&mut self) { + if let Some(s) = self.state.take() { + self.state = Some(s.approve()) + } + } +} + +// ANCHOR: here +trait State { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box; + fn approve(self: Box) -> Box; + + // ANCHOR: here + fn content<'a>(&self, post: &'a Post) -> &'a str { + "" + } +} + +// --snip-- +// ANCHOR_END: here + +struct Draft {} + +impl State for Draft { + fn request_review(self: Box) -> Box { + Box::new(PendingReview {}) + } + + fn approve(self: Box) -> Box { + self + } +} + +struct PendingReview {} + +impl State for PendingReview { + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + Box::new(Published {}) + } +} + +// ANCHOR: here +struct Published {} + +impl State for Published { + // --snip-- + // ANCHOR_END: here + fn request_review(self: Box) -> Box { + self + } + + fn approve(self: Box) -> Box { + self + } + + // ANCHOR: here + fn content<'a>(&self, post: &'a Post) -> &'a str { + &post.content + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-18/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-18/src/main.rs new file mode 100644 index 0000000000..14b4c0824c --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-18/src/main.rs @@ -0,0 +1,14 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + + post.approve(); + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-19/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-19/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-19/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-19/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-19/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-19/src/lib.rs new file mode 100644 index 0000000000..bfe034eaf1 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-19/src/lib.rs @@ -0,0 +1,25 @@ +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-20/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-20/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-20/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-20/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-20/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-20/src/lib.rs new file mode 100644 index 0000000000..3b82ec05dc --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-20/src/lib.rs @@ -0,0 +1,48 @@ +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +// ANCHOR: here +impl DraftPost { + // --snip-- + // ANCHOR_END: here + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + // ANCHOR: here + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +pub struct PendingReviewPost { + content: String, +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch17-oop/listing-17-21/Cargo.lock b/src/doc/book/listings/ch17-oop/listing-17-21/Cargo.lock new file mode 100644 index 0000000000..b6f4232c60 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/listing-17-21/Cargo.toml b/src/doc/book/listings/ch17-oop/listing-17-21/Cargo.toml new file mode 100644 index 0000000000..9a395e23ad --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/listing-17-21/src/lib.rs b/src/doc/book/listings/ch17-oop/listing-17-21/src/lib.rs new file mode 100644 index 0000000000..38500a651b --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-21/src/lib.rs @@ -0,0 +1,43 @@ +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +pub struct PendingReviewPost { + content: String, +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} diff --git a/src/doc/book/listings/ch17-oop/listing-17-21/src/main.rs b/src/doc/book/listings/ch17-oop/listing-17-21/src/main.rs new file mode 100644 index 0000000000..720c55e6aa --- /dev/null +++ b/src/doc/book/listings/ch17-oop/listing-17-21/src/main.rs @@ -0,0 +1,13 @@ +use blog::Post; + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + + let post = post.request_review(); + + let post = post.approve(); + + assert_eq!("I ate a salad for lunch today", post.content()); +} diff --git a/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock new file mode 100644 index 0000000000..00d7b21826 --- /dev/null +++ b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "gui" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml new file mode 100644 index 0000000000..1f61cd20ec --- /dev/null +++ b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "gui" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt new file mode 100644 index 0000000000..33a492556d --- /dev/null +++ b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt @@ -0,0 +1,16 @@ +$ cargo build + Compiling gui v0.1.0 (file:///projects/gui) +error[E0038]: the trait `std::clone::Clone` cannot be made into an object + --> src/lib.rs:2:5 + | +2 | pub components: Vec>, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` cannot be made into an object + | + = note: the trait cannot require that `Self : Sized` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0038`. +error: could not compile `gui`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs new file mode 100644 index 0000000000..e6b1a37f0a --- /dev/null +++ b/src/doc/book/listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs @@ -0,0 +1,3 @@ +pub struct Screen { + pub components: Vec>, +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs new file mode 100644 index 0000000000..d28c369f56 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-01/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + let favorite_color: Option<&str> = None; + let is_tuesday = false; + let age: Result = "34".parse(); + + if let Some(color) = favorite_color { + println!("Using your favorite color, {}, as the background", color); + } else if is_tuesday { + println!("Tuesday is green day!"); + } else if let Ok(age) = age { + if age > 30 { + println!("Using purple as the background color"); + } else { + println!("Using orange as the background color"); + } + } else { + println!("Using blue as the background color"); + } +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs new file mode 100644 index 0000000000..5f75a4f2db --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-02/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let mut stack = Vec::new(); + + stack.push(1); + stack.push(2); + stack.push(3); + + while let Some(top) = stack.pop() { + println!("{}", top); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/output.txt b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/output.txt new file mode 100644 index 0000000000..02fdecbf5c --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) + Finished dev [unoptimized + debuginfo] target(s) in 0.52s + Running `target/debug/patterns` +a is at index 0 +b is at index 1 +c is at index 2 diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs new file mode 100644 index 0000000000..eb922d62cd --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-03/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + let v = vec!['a', 'b', 'c']; + + for (index, value) in v.iter().enumerate() { + println!("{} is at index {}", value, index); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs new file mode 100644 index 0000000000..27b0c3fbdc --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-04/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let (x, y, z) = (1, 2, 3); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/output.txt b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/output.txt new file mode 100644 index 0000000000..eae835e37c --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +error[E0308]: mismatched types + --> src/main.rs:2:9 + | +2 | let (x, y) = (1, 2, 3); + | ^^^^^^ expected a tuple with 3 elements, found one with 2 elements + | + = note: expected tuple `({integer}, {integer}, {integer})` + found tuple `(_, _)` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. +error: could not compile `patterns`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs new file mode 100644 index 0000000000..39f768e29e --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-05/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + // ANCHOR: here + let (x, y) = (1, 2, 3); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs new file mode 100644 index 0000000000..c5d71e6c13 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-06/src/main.rs @@ -0,0 +1,7 @@ +// ANCHOR: here +fn foo(x: i32) { + // code goes here +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs new file mode 100644 index 0000000000..4eccb8088c --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-07/src/main.rs @@ -0,0 +1,8 @@ +fn print_coordinates(&(x, y): &(i32, i32)) { + println!("Current location: ({}, {})", x, y); +} + +fn main() { + let point = (3, 5); + print_coordinates(&point); +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt new file mode 100644 index 0000000000..551250ff87 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/output.txt @@ -0,0 +1,21 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +error[E0005]: refutable pattern in local binding: `None` not covered + --> src/main.rs:3:9 + | +3 | let Some(x) = some_option_value; + | ^^^^^^^ pattern `None` not covered + | + = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant + = note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html +help: you might want to use `if let` to ignore the variant that isn't matched + | +3 | if let Some(x) = some_option_value { /* */ } + | + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0005`. +error: could not compile `patterns`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs new file mode 100644 index 0000000000..7baa02a49b --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-08/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let some_option_value: Option = None; + // ANCHOR: here + let Some(x) = some_option_value; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs new file mode 100644 index 0000000000..d6274fc0e1 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-09/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + let some_option_value: Option = None; + // ANCHOR: here + if let Some(x) = some_option_value { + println!("{}", x); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/output.txt b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/output.txt new file mode 100644 index 0000000000..8b72e18134 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/output.txt @@ -0,0 +1,15 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +warning: irrefutable if-let pattern + --> src/main.rs:2:5 + | +2 | / if let x = 5 { +3 | | println!("{}", x); +4 | | }; + | |_____^ + | + = note: `#[warn(irrefutable_let_patterns)]` on by default + + Finished dev [unoptimized + debuginfo] target(s) in 0.39s + Running `target/debug/patterns` +5 diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs new file mode 100644 index 0000000000..cb81772e0c --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-10/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + if let x = 5 { + println!("{}", x); + }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs new file mode 100644 index 0000000000..25eaa79ff8 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-11/src/main.rs @@ -0,0 +1,14 @@ +fn main() { + // ANCHOR: here + let x = Some(5); + let y = 10; + + match x { + Some(50) => println!("Got 50"), + Some(y) => println!("Matched, y = {:?}", y), + _ => println!("Default case, x = {:?}", x), + } + + println!("at the end: x = {:?}, y = {:?}", x, y); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs new file mode 100644 index 0000000000..62f4ccbf1e --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-12/src/main.rs @@ -0,0 +1,12 @@ +struct Point { + x: i32, + y: i32, +} + +fn main() { + let p = Point { x: 0, y: 7 }; + + let Point { x: a, y: b } = p; + assert_eq!(0, a); + assert_eq!(7, b); +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs new file mode 100644 index 0000000000..5badc1594f --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-13/src/main.rs @@ -0,0 +1,12 @@ +struct Point { + x: i32, + y: i32, +} + +fn main() { + let p = Point { x: 0, y: 7 }; + + let Point { x, y } = p; + assert_eq!(0, x); + assert_eq!(7, y); +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs new file mode 100644 index 0000000000..8d445d9b9d --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-14/src/main.rs @@ -0,0 +1,16 @@ +struct Point { + x: i32, + y: i32, +} + +// ANCHOR: here +fn main() { + let p = Point { x: 0, y: 7 }; + + match p { + Point { x, y: 0 } => println!("On the x axis at {}", x), + Point { x: 0, y } => println!("On the y axis at {}", y), + Point { x, y } => println!("On neither axis: ({}, {})", x, y), + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs new file mode 100644 index 0000000000..9b8dac1938 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-15/src/main.rs @@ -0,0 +1,27 @@ +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), +} + +fn main() { + let msg = Message::ChangeColor(0, 160, 255); + + match msg { + Message::Quit => { + println!("The Quit variant has no data to destructure.") + } + Message::Move { x, y } => { + println!( + "Move in the x direction {} and in the y direction {}", + x, y + ); + } + Message::Write(text) => println!("Text message: {}", text), + Message::ChangeColor(r, g, b) => println!( + "Change the color to red {}, green {}, and blue {}", + r, g, b + ), + } +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs new file mode 100644 index 0000000000..ed6a20bf47 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-16/src/main.rs @@ -0,0 +1,27 @@ +enum Color { + Rgb(i32, i32, i32), + Hsv(i32, i32, i32), +} + +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(Color), +} + +fn main() { + let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); + + match msg { + Message::ChangeColor(Color::Rgb(r, g, b)) => println!( + "Change the color to red {}, green {}, and blue {}", + r, g, b + ), + Message::ChangeColor(Color::Hsv(h, s, v)) => println!( + "Change the color to hue {}, saturation {}, and value {}", + h, s, v + ), + _ => (), + } +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs new file mode 100644 index 0000000000..cf1fbe0721 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-17/src/main.rs @@ -0,0 +1,7 @@ +fn foo(_: i32, y: i32) { + println!("This code only uses the y parameter: {}", y); +} + +fn main() { + foo(3, 4); +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs new file mode 100644 index 0000000000..b776c64c42 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-18/src/main.rs @@ -0,0 +1,17 @@ +fn main() { + // ANCHOR: here + let mut setting_value = Some(5); + let new_setting_value = Some(10); + + match (setting_value, new_setting_value) { + (Some(_), Some(_)) => { + println!("Can't overwrite an existing customized value"); + } + _ => { + setting_value = new_setting_value; + } + } + + println!("setting is {:?}", setting_value); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs new file mode 100644 index 0000000000..59b48c94d8 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-19/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let numbers = (2, 4, 8, 16, 32); + + match numbers { + (first, _, third, _, fifth) => { + println!("Some numbers: {}, {}, {}", first, third, fifth) + } + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs new file mode 100644 index 0000000000..1ffc46bad3 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-20/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let _x = 5; + let y = 10; +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs new file mode 100644 index 0000000000..980610503f --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-21/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let s = Some(String::from("Hello!")); + + if let Some(_s) = s { + println!("found a string"); + } + + println!("{:?}", s); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs new file mode 100644 index 0000000000..e2faa345bc --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-22/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let s = Some(String::from("Hello!")); + + if let Some(_) = s { + println!("found a string"); + } + + println!("{:?}", s); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs new file mode 100644 index 0000000000..7a9d9bb36f --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-23/src/main.rs @@ -0,0 +1,15 @@ +fn main() { + // ANCHOR: here + struct Point { + x: i32, + y: i32, + z: i32, + } + + let origin = Point { x: 0, y: 0, z: 0 }; + + match origin { + Point { x, .. } => println!("x is {}", x), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs new file mode 100644 index 0000000000..f22dbe8edf --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-24/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let numbers = (2, 4, 8, 16, 32); + + match numbers { + (first, .., last) => { + println!("Some numbers: {}, {}", first, last); + } + } +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock new file mode 100644 index 0000000000..a233623e55 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/output.txt b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/output.txt new file mode 100644 index 0000000000..3044c4b30c --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/output.txt @@ -0,0 +1,15 @@ +$ cargo run + Compiling patterns v0.1.0 (file:///projects/patterns) +error: `..` can only be used once per tuple pattern + --> src/main.rs:5:22 + | +5 | (.., second, ..) => { + | -- ^^ can only be used once per tuple pattern + | | + | previously used here + +error: aborting due to previous error + +error: could not compile `patterns`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore new file mode 100644 index 0000000000..06a976dd46 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/rustfmt-ignore @@ -0,0 +1 @@ +This listing deliberately doesn't parse so rustfmt fails. diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs new file mode 100644 index 0000000000..b90884eb9c --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-25/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let numbers = (2, 4, 8, 16, 32); + + match numbers { + (.., second, ..) => { + println!("Some numbers: {}", second) + }, + } +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs new file mode 100644 index 0000000000..4ec86cba76 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-26/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let num = Some(4); + + match num { + Some(x) if x < 5 => println!("less than five: {}", x), + Some(x) => println!("{}", x), + None => (), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs new file mode 100644 index 0000000000..348e367233 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-27/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + let x = Some(5); + let y = 10; + + match x { + Some(50) => println!("Got 50"), + Some(n) if n == y => println!("Matched, n = {}", n), + _ => println!("Default case, x = {:?}", x), + } + + println!("at the end: x = {:?}, y = {}", x, y); +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs new file mode 100644 index 0000000000..15804553fa --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-28/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let x = 4; + let y = false; + + match x { + 4 | 5 | 6 if y => println!("yes"), + _ => println!("no"), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs new file mode 100644 index 0000000000..3514deb636 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/listing-18-29/src/main.rs @@ -0,0 +1,19 @@ +fn main() { + // ANCHOR: here + enum Message { + Hello { id: i32 }, + } + + let msg = Message::Hello { id: 5 }; + + match msg { + Message::Hello { + id: id_variable @ 3..=7, + } => println!("Found an id in range: {}", id_variable), + Message::Hello { id: 10..=12 } => { + println!("Found an id in another range") + } + Message::Hello { id } => println!("Found some other id: {}", id), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs new file mode 100644 index 0000000000..7978e1adeb --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + let x = 1; + + match x { + 1 => println!("one"), + 2 => println!("two"), + 3 => println!("three"), + _ => println!("anything"), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs new file mode 100644 index 0000000000..e52d815d84 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let x = 1; + + match x { + 1 | 2 => println!("one or two"), + 3 => println!("three"), + _ => println!("anything"), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs new file mode 100644 index 0000000000..a3ebe7af06 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + let x = 5; + + match x { + 1..=5 => println!("one through five"), + _ => println!("something else"), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs new file mode 100644 index 0000000000..8cebfef5ed --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs @@ -0,0 +1,11 @@ +fn main() { + // ANCHOR: here + let x = 'c'; + + match x { + 'a'..='j' => println!("early ASCII letter"), + 'k'..='z' => println!("late ASCII letter"), + _ => println!("something else"), + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock new file mode 100644 index 0000000000..2b4fa29032 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml new file mode 100644 index 0000000000..f77be077b9 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs new file mode 100644 index 0000000000..962d093491 --- /dev/null +++ b/src/doc/book/listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + struct Point { + x: i32, + y: i32, + } + + // ANCHOR: here + let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock new file mode 100644 index 0000000000..58b70c5b74 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "counter" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml new file mode 100644 index 0000000000..4eb29e80c1 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "counter" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs new file mode 100644 index 0000000000..b71b54fbce --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs @@ -0,0 +1,27 @@ +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +// ANCHOR: ch19 +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option { + // --snip-- + // ANCHOR_END: ch19 + if self.count < 5 { + self.count += 1; + Some(self.count) + } else { + None + } + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-01/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-01/src/main.rs new file mode 100644 index 0000000000..893f578905 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-01/src/main.rs @@ -0,0 +1,8 @@ +fn main() { + // ANCHOR: here + let mut num = 5; + + let r1 = &num as *const i32; + let r2 = &mut num as *mut i32; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-02/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-02/src/main.rs new file mode 100644 index 0000000000..849629a7cc --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-02/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let address = 0x012345usize; + let r = address as *const i32; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-03/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-03/src/main.rs new file mode 100644 index 0000000000..02a0be6b0e --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-03/src/main.rs @@ -0,0 +1,13 @@ +fn main() { + // ANCHOR: here + let mut num = 5; + + let r1 = &num as *const i32; + let r2 = &mut num as *mut i32; + + unsafe { + println!("r1 is: {}", *r1); + println!("r2 is: {}", *r2); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-04/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-04/src/main.rs new file mode 100644 index 0000000000..6ac58442db --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-04/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: here + let mut v = vec![1, 2, 3, 4, 5, 6]; + + let r = &mut v[..]; + + let (a, b) = r.split_at_mut(3); + + assert_eq!(a, &mut [1, 2, 3]); + assert_eq!(b, &mut [4, 5, 6]); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-05/output.txt b/src/doc/book/listings/ch19-advanced-features/listing-19-05/output.txt new file mode 100644 index 0000000000..3df0e2b64c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-05/output.txt @@ -0,0 +1,21 @@ +$ cargo run + Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example) +error[E0499]: cannot borrow `*slice` as mutable more than once at a time + --> src/main.rs:6:30 + | +1 | fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { + | - let's call the lifetime of this reference `'1` +... +6 | (&mut slice[..mid], &mut slice[mid..]) + | -------------------------^^^^^-------- + | | | | + | | | second mutable borrow occurs here + | | first mutable borrow occurs here + | returning this value requires that `*slice` is borrowed for `'1` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0499`. +error: could not compile `unsafe-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-05/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-05/src/main.rs new file mode 100644 index 0000000000..c4b83effaf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-05/src/main.rs @@ -0,0 +1,14 @@ +// ANCHOR: here +fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { + let len = slice.len(); + + assert!(mid <= len); + + (&mut slice[..mid], &mut slice[mid..]) +} +// ANCHOR_END: here + +fn main() { + let mut vector = vec![1, 2, 3, 4, 5, 6]; + let (left, right) = split_at_mut(&mut vector, 3); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-06/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-06/src/main.rs new file mode 100644 index 0000000000..f25cbf49d9 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-06/src/main.rs @@ -0,0 +1,22 @@ +// ANCHOR: here +use std::slice; + +fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { + let len = slice.len(); + let ptr = slice.as_mut_ptr(); + + assert!(mid <= len); + + unsafe { + ( + slice::from_raw_parts_mut(ptr, mid), + slice::from_raw_parts_mut(ptr.add(mid), len - mid), + ) + } +} +// ANCHOR_END: here + +fn main() { + let mut vector = vec![1, 2, 3, 4, 5, 6]; + let (left, right) = split_at_mut(&mut vector, 3); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-07/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-07/src/main.rs new file mode 100644 index 0000000000..0ab39ae1d2 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-07/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + use std::slice; + + let address = 0x01234usize; + let r = address as *mut i32; + + let slice: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-08/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-08/src/main.rs new file mode 100644 index 0000000000..8b56630c95 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-08/src/main.rs @@ -0,0 +1,9 @@ +extern "C" { + fn abs(input: i32) -> i32; +} + +fn main() { + unsafe { + println!("Absolute value of -3 according to C: {}", abs(-3)); + } +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-09/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-09/src/main.rs new file mode 100644 index 0000000000..82a4b4219f --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-09/src/main.rs @@ -0,0 +1,5 @@ +static HELLO_WORLD: &str = "Hello, world!"; + +fn main() { + println!("name is: {}", HELLO_WORLD); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-10/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-10/src/main.rs new file mode 100644 index 0000000000..e8dab68e0d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-10/src/main.rs @@ -0,0 +1,15 @@ +static mut COUNTER: u32 = 0; + +fn add_to_count(inc: u32) { + unsafe { + COUNTER += inc; + } +} + +fn main() { + add_to_count(3); + + unsafe { + println!("COUNTER: {}", COUNTER); + } +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-11/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-11/src/main.rs new file mode 100644 index 0000000000..885c1aa1d8 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-11/src/main.rs @@ -0,0 +1,9 @@ +unsafe trait Foo { + // methods go here +} + +unsafe impl Foo for i32 { + // method implementations go here +} + +fn main() {} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-12/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-12/src/lib.rs new file mode 100644 index 0000000000..dbe04620ef --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-12/src/lib.rs @@ -0,0 +1,5 @@ +pub trait Iterator { + type Item; + + fn next(&mut self) -> Option; +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-13/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-13/src/lib.rs new file mode 100644 index 0000000000..7c9479c5b5 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-13/src/lib.rs @@ -0,0 +1,3 @@ +pub trait Iterator { + fn next(&mut self) -> Option; +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-14/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-14/src/main.rs new file mode 100644 index 0000000000..7dea568d92 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-14/src/main.rs @@ -0,0 +1,25 @@ +use std::ops::Add; + +#[derive(Debug, PartialEq)] +struct Point { + x: i32, + y: i32, +} + +impl Add for Point { + type Output = Point; + + fn add(self, other: Point) -> Point { + Point { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +fn main() { + assert_eq!( + Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, + Point { x: 3, y: 3 } + ); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-15/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-15/src/lib.rs new file mode 100644 index 0000000000..f38bf475c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-15/src/lib.rs @@ -0,0 +1,12 @@ +use std::ops::Add; + +struct Millimeters(u32); +struct Meters(u32); + +impl Add for Millimeters { + type Output = Millimeters; + + fn add(self, other: Meters) -> Millimeters { + Millimeters(self.0 + (other.0 * 1000)) + } +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-16/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-16/src/main.rs new file mode 100644 index 0000000000..d854e287df --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-16/src/main.rs @@ -0,0 +1,31 @@ +// ANCHOR: here +trait Pilot { + fn fly(&self); +} + +trait Wizard { + fn fly(&self); +} + +struct Human; + +impl Pilot for Human { + fn fly(&self) { + println!("This is your captain speaking."); + } +} + +impl Wizard for Human { + fn fly(&self) { + println!("Up!"); + } +} + +impl Human { + fn fly(&self) { + println!("*waving arms furiously*"); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-17/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-17/src/main.rs new file mode 100644 index 0000000000..3df65a7ce2 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-17/src/main.rs @@ -0,0 +1,34 @@ +trait Pilot { + fn fly(&self); +} + +trait Wizard { + fn fly(&self); +} + +struct Human; + +impl Pilot for Human { + fn fly(&self) { + println!("This is your captain speaking."); + } +} + +impl Wizard for Human { + fn fly(&self) { + println!("Up!"); + } +} + +impl Human { + fn fly(&self) { + println!("*waving arms furiously*"); + } +} + +// ANCHOR: here +fn main() { + let person = Human; + person.fly(); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-18/output.txt b/src/doc/book/listings/ch19-advanced-features/listing-19-18/output.txt new file mode 100644 index 0000000000..2e9da17d65 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-18/output.txt @@ -0,0 +1,7 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.46s + Running `target/debug/traits-example` +This is your captain speaking. +Up! +*waving arms furiously* diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-18/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-18/src/main.rs new file mode 100644 index 0000000000..fa01c09ccc --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-18/src/main.rs @@ -0,0 +1,36 @@ +trait Pilot { + fn fly(&self); +} + +trait Wizard { + fn fly(&self); +} + +struct Human; + +impl Pilot for Human { + fn fly(&self) { + println!("This is your captain speaking."); + } +} + +impl Wizard for Human { + fn fly(&self) { + println!("Up!"); + } +} + +impl Human { + fn fly(&self) { + println!("*waving arms furiously*"); + } +} + +// ANCHOR: here +fn main() { + let person = Human; + Pilot::fly(&person); + Wizard::fly(&person); + person.fly(); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-19/output.txt b/src/doc/book/listings/ch19-advanced-features/listing-19-19/output.txt new file mode 100644 index 0000000000..087e802b1a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-19/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.54s + Running `target/debug/traits-example` +A baby dog is called a Spot diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-19/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-19/src/main.rs new file mode 100644 index 0000000000..44affe0ee2 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-19/src/main.rs @@ -0,0 +1,21 @@ +trait Animal { + fn baby_name() -> String; +} + +struct Dog; + +impl Dog { + fn baby_name() -> String { + String::from("Spot") + } +} + +impl Animal for Dog { + fn baby_name() -> String { + String::from("puppy") + } +} + +fn main() { + println!("A baby dog is called a {}", Dog::baby_name()); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt b/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt new file mode 100644 index 0000000000..46c7dafa0a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-20/output.txt @@ -0,0 +1,19 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) +error[E0283]: type annotations needed + --> src/main.rs:20:43 + | +2 | fn baby_name() -> String; + | ------------------------- required by `Animal::baby_name` +... +20 | println!("A baby dog is called a {}", Animal::baby_name()); + | ^^^^^^^^^^^^^^^^^ cannot infer type + | + = note: cannot resolve `_: Animal` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0283`. +error: could not compile `traits-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-20/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-20/src/main.rs new file mode 100644 index 0000000000..8e295c9b65 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-20/src/main.rs @@ -0,0 +1,23 @@ +trait Animal { + fn baby_name() -> String; +} + +struct Dog; + +impl Dog { + fn baby_name() -> String { + String::from("Spot") + } +} + +impl Animal for Dog { + fn baby_name() -> String { + String::from("puppy") + } +} + +// ANCHOR: here +fn main() { + println!("A baby dog is called a {}", Animal::baby_name()); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-21/output.txt b/src/doc/book/listings/ch19-advanced-features/listing-19-21/output.txt new file mode 100644 index 0000000000..4d1ee5ab48 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-21/output.txt @@ -0,0 +1,5 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) + Finished dev [unoptimized + debuginfo] target(s) in 0.48s + Running `target/debug/traits-example` +A baby dog is called a puppy diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-21/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-21/src/main.rs new file mode 100644 index 0000000000..b1df728951 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-21/src/main.rs @@ -0,0 +1,23 @@ +trait Animal { + fn baby_name() -> String; +} + +struct Dog; + +impl Dog { + fn baby_name() -> String { + String::from("Spot") + } +} + +impl Animal for Dog { + fn baby_name() -> String { + String::from("puppy") + } +} + +// ANCHOR: here +fn main() { + println!("A baby dog is called a {}", ::baby_name()); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-22/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-22/src/main.rs new file mode 100644 index 0000000000..febe58b0c5 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-22/src/main.rs @@ -0,0 +1,17 @@ +// ANCHOR: here +use std::fmt; + +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-23/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-23/src/main.rs new file mode 100644 index 0000000000..eae46c92f3 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-23/src/main.rs @@ -0,0 +1,14 @@ +use std::fmt; + +struct Wrapper(Vec); + +impl fmt::Display for Wrapper { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[{}]", self.0.join(", ")) + } +} + +fn main() { + let w = Wrapper(vec![String::from("hello"), String::from("world")]); + println!("w = {}", w); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-24/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-24/src/main.rs new file mode 100644 index 0000000000..d604ae8d6a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-24/src/main.rs @@ -0,0 +1,16 @@ +fn main() { + // ANCHOR: here + let f: Box = Box::new(|| println!("hi")); + + fn takes_long_type(f: Box) { + // --snip-- + } + + fn returns_long_type() -> Box { + // --snip-- + // ANCHOR_END: here + Box::new(|| ()) + // ANCHOR: here + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-25/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-25/src/main.rs new file mode 100644 index 0000000000..af35bed2c9 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-25/src/main.rs @@ -0,0 +1,18 @@ +fn main() { + // ANCHOR: here + type Thunk = Box; + + let f: Thunk = Box::new(|| println!("hi")); + + fn takes_long_type(f: Thunk) { + // --snip-- + } + + fn returns_long_type() -> Thunk { + // --snip-- + // ANCHOR_END: here + Box::new(|| ()) + // ANCHOR: here + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-27/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-27/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-27/src/main.rs new file mode 100644 index 0000000000..91b2cf04bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-27/src/main.rs @@ -0,0 +1,13 @@ +fn add_one(x: i32) -> i32 { + x + 1 +} + +fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { + f(arg) + f(arg) +} + +fn main() { + let answer = do_twice(add_one, 5); + + println!("The answer is: {}", answer); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.lock new file mode 100644 index 0000000000..b2d9257545 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "macros-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.toml new file mode 100644 index 0000000000..1829b0fa66 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-28/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "macros-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-28/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-28/src/lib.rs new file mode 100644 index 0000000000..7c7c4756c8 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-28/src/lib.rs @@ -0,0 +1,12 @@ +#[macro_export] +macro_rules! vec { + ( $( $x:expr ),* ) => { + { + let mut temp_vec = Vec::new(); + $( + temp_vec.push($x); + )* + temp_vec + } + }; +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-30/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-30/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-30/src/main.rs new file mode 100644 index 0000000000..468c30aa48 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-30/src/main.rs @@ -0,0 +1,9 @@ +use hello_macro::HelloMacro; +use hello_macro_derive::HelloMacro; + +#[derive(HelloMacro)] +struct Pancakes; + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock new file mode 100644 index 0000000000..9a38c8ac26 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000000..168cbae53c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[lib] +proc-macro = true + +[dependencies] +syn = "1.0" +quote = "1.0" diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000000..4bcec44e98 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,15 @@ +extern crate proc_macro; + +use proc_macro::TokenStream; +use quote::quote; +use syn; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-31/hello_macro/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock new file mode 100644 index 0000000000..9a38c8ac26 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000000..168cbae53c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[lib] +proc-macro = true + +[dependencies] +syn = "1.0" +quote = "1.0" diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000000..591f0c3591 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,29 @@ +extern crate proc_macro; + +use proc_macro::TokenStream; +use quote::quote; +use syn; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} + +// ANCHOR: here +fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { + let name = &ast.ident; + let gen = quote! { + impl HelloMacro for #name { + fn hello_macro() { + println!("Hello, Macro! My name is {}!", stringify!(#name)); + } + } + }; + gen.into() +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/listing-19-33/hello_macro/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs new file mode 100644 index 0000000000..21ecdbe5af --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + unsafe fn dangerous() {} + + unsafe { + dangerous(); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt new file mode 100644 index 0000000000..e7a028e351 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt @@ -0,0 +1,17 @@ +$ cargo run + Compiling traits-example v0.1.0 (file:///projects/traits-example) +error[E0277]: `Point` doesn't implement `std::fmt::Display` + --> src/main.rs:20:6 + | +20 | impl OutlinePrint for Point {} + | ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter + | + = help: the trait `std::fmt::Display` is not implemented for `Point` + = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. +error: could not compile `traits-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs new file mode 100644 index 0000000000..a1e2fe4c46 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs @@ -0,0 +1,27 @@ +use std::fmt; + +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} + +// ANCHOR: here +struct Point { + x: i32, + y: i32, +} + +impl OutlinePrint for Point {} +// ANCHOR_END: here + +fn main() { + let p = Point { x: 1, y: 3 }; + p.outline_print(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs new file mode 100644 index 0000000000..c7bbb6a708 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs @@ -0,0 +1,33 @@ +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {} *", output); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} + +struct Point { + x: i32, + y: i32, +} + +impl OutlinePrint for Point {} + +// ANCHOR: here +use std::fmt; + +impl fmt::Display for Point { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({}, {})", self.x, self.y) + } +} +// ANCHOR_END: here + +fn main() { + let p = Point { x: 1, y: 3 }; + p.outline_print(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs new file mode 100644 index 0000000000..d3fe32e2f0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + // ANCHOR: there + // ANCHOR: here + type Kilometers = i32; + // ANCHOR_END: here + + let x: i32 = 5; + let y: Kilometers = 5; + + println!("x + y = {}", x + y); + // ANCHOR_END: there +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs new file mode 100644 index 0000000000..8300dcceee --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs @@ -0,0 +1,10 @@ +use std::fmt; +use std::io::Error; + +pub trait Write { + fn write(&mut self, buf: &[u8]) -> Result; + fn flush(&mut self) -> Result<(), Error>; + + fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>; + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>; +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs new file mode 100644 index 0000000000..c53a927e32 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs @@ -0,0 +1,17 @@ +use std::fmt; + +// ANCHOR: here +type Result = std::result::Result; +// ANCHOR_END: here + +// ANCHOR: there +pub trait Write { + fn write(&mut self, buf: &[u8]) -> Result; + fn flush(&mut self) -> Result<()>; + + fn write_all(&mut self, buf: &[u8]) -> Result<()>; + fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>; +} +// ANCHOR_END: there + +fn main() {} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock new file mode 100644 index 0000000000..b1977d01ec --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "traits-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml new file mode 100644 index 0000000000..1e3df0242d --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs new file mode 100644 index 0000000000..236224186e --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +fn bar() -> ! { + // --snip-- + // ANCHOR_END: here + panic!(); + // ANCHOR: here +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs new file mode 100644 index 0000000000..6d56008add --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + let guess = "3"; + // ANCHOR: here + let guess = match guess.trim().parse() { + Ok(_) => 5, + Err(_) => "hello", + }; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs new file mode 100644 index 0000000000..aa4f937ff0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs @@ -0,0 +1,17 @@ +enum Option { + Some(T), + None, +} + +use crate::Option::*; + +// ANCHOR: here +impl Option { + pub fn unwrap(self) -> T { + match self { + Some(val) => val, + None => panic!("called `Option::unwrap()` on a `None` value"), + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs new file mode 100644 index 0000000000..e7768913b7 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs @@ -0,0 +1,9 @@ +fn main() { + // ANCHOR: here + print!("forever "); + + loop { + print!("and ever "); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs new file mode 100644 index 0000000000..075d5110c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + // ANCHOR: here + let s1: str = "Hello there!"; + let s2: str = "How's it going?"; + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs new file mode 100644 index 0000000000..69186ddfb6 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs @@ -0,0 +1,3 @@ +fn generic(t: T) { + // --snip-- +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs new file mode 100644 index 0000000000..c2d00e2163 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs @@ -0,0 +1,3 @@ +fn generic(t: T) { + // --snip-- +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock new file mode 100644 index 0000000000..c0c98a79cf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "types-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml new file mode 100644 index 0000000000..9b4ee689bf --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "types-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs new file mode 100644 index 0000000000..e4722267ab --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs @@ -0,0 +1,3 @@ +fn generic(t: &T) { + // --snip-- +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs new file mode 100644 index 0000000000..b4fcf7eb85 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let list_of_numbers = vec![1, 2, 3]; + let list_of_strings: Vec = + list_of_numbers.iter().map(|i| i.to_string()).collect(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs new file mode 100644 index 0000000000..dff20fe71b --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + let list_of_numbers = vec![1, 2, 3]; + let list_of_strings: Vec = + list_of_numbers.iter().map(ToString::to_string).collect(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs new file mode 100644 index 0000000000..60fb730057 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + // ANCHOR: here + enum Status { + Value(u32), + Stop, + } + + let list_of_statuses: Vec = (0u32..20).map(Status::Value).collect(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt new file mode 100644 index 0000000000..2d4be9b0a3 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt @@ -0,0 +1,30 @@ +$ cargo build + Compiling functions-example v0.1.0 (file:///projects/functions-example) +error[E0277]: the size for values of type `(dyn std::ops::Fn(i32) -> i32 + 'static)` cannot be known at compilation time + --> src/lib.rs:1:25 + | +1 | fn returns_closure() -> dyn Fn(i32) -> i32 { + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `std::marker::Sized` is not implemented for `(dyn std::ops::Fn(i32) -> i32 + 'static)` + = note: to learn more, visit + = note: the return type of a function must have a statically known size + +error[E0308]: mismatched types + --> src/lib.rs:2:5 + | +1 | fn returns_closure() -> dyn Fn(i32) -> i32 { + | ------------------ expected `(dyn std::ops::Fn(i32) -> i32 + 'static)` because of return type +2 | |x| x + 1 + | ^^^^^^^^^ expected trait `std::ops::Fn`, found closure + | + = note: expected trait object `(dyn std::ops::Fn(i32) -> i32 + 'static)` + found closure `[closure@src/lib.rs:2:5: 2:14]` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0277, E0308. +For more information about an error, try `rustc --explain E0277`. +error: could not compile `functions-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs new file mode 100644 index 0000000000..d699ac34eb --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs @@ -0,0 +1,3 @@ +fn returns_closure() -> dyn Fn(i32) -> i32 { + |x| x + 1 +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock new file mode 100644 index 0000000000..b2327c755a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "functions-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml new file mode 100644 index 0000000000..2bed56c367 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs new file mode 100644 index 0000000000..b114077472 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs @@ -0,0 +1,3 @@ +fn returns_closure() -> Box i32> { + Box::new(|x| x + 1) +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock new file mode 100644 index 0000000000..881cd3f6df --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.lock @@ -0,0 +1,13 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + +[[package]] +name = "pancakes" +version = "0.1.0" +dependencies = [ + "hello_macro 0.1.0", +] + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml new file mode 100644 index 0000000000..4b6c267b42 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "pancakes" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +hello_macro = { path = "../hello_macro" } \ No newline at end of file diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock new file mode 100644 index 0000000000..39afcf282f --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml new file mode 100644 index 0000000000..5a93a685c0 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_macro" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock new file mode 100644 index 0000000000..9a38c8ac26 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000000..168cbae53c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[lib] +proc-macro = true + +[dependencies] +syn = "1.0" +quote = "1.0" diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000000..7a3279d864 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,27 @@ +extern crate proc_macro; + +use proc_macro::TokenStream; +use quote::quote; +use syn; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} + +fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { + let name = &ast.ident; + let gen = quote! { + impl HelloMacro for #name { + fn hello_macro() { + println!("Hello, Macro! My name is {}!", stringify!(#name)); + } + } + }; + gen.into() +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs new file mode 100644 index 0000000000..e74793184b --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs new file mode 100644 index 0000000000..10b028b2d4 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/hello_macro/src/main.rs @@ -0,0 +1,13 @@ +use hello_macro::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("Hello, Macro! My name is Pancakes!"); + } +} + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock new file mode 100644 index 0000000000..dee23ecf96 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.lock @@ -0,0 +1,58 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello_macro" +version = "0.1.0" + +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "pancakes" +version = "0.1.0" +dependencies = [ + "hello_macro 0.1.0", + "hello_macro_derive 0.1.0", +] + +[[package]] +name = "proc-macro2" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml new file mode 100644 index 0000000000..cc0addaa4a --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "pancakes" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] +hello_macro = { path = "../hello_macro" } +hello_macro_derive = { path = "../hello_macro/hello_macro_derive" } diff --git a/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs new file mode 100644 index 0000000000..468c30aa48 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/src/main.rs @@ -0,0 +1,9 @@ +use hello_macro::HelloMacro; +use hello_macro_derive::HelloMacro; + +#[derive(HelloMacro)] +struct Pancakes; + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock new file mode 100644 index 0000000000..497817bf27 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "unsafe-example" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml new file mode 100644 index 0000000000..aabe3bdf5c --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-example" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt new file mode 100644 index 0000000000..bfe082a8b9 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt @@ -0,0 +1,16 @@ +$ cargo run + Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example) +error[E0133]: call to unsafe function is unsafe and requires unsafe function or block + --> src/main.rs:4:5 + | +4 | dangerous(); + | ^^^^^^^^^^^ call to unsafe function + | + = note: consult the function's documentation for information on how to avoid undefined behavior + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0133`. +error: could not compile `unsafe-example`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs new file mode 100644 index 0000000000..01305be749 --- /dev/null +++ b/src/doc/book/listings/ch19-advanced-features/output-only-01-missing-unsafe/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + // ANCHOR: here + unsafe fn dangerous() {} + + dangerous(); + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-01/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-01/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-01/src/main.rs new file mode 100644 index 0000000000..d868c3ec16 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-01/src/main.rs @@ -0,0 +1,11 @@ +use std::net::TcpListener; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + println!("Connection established!"); + } +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-02/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-02/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-02/src/main.rs new file mode 100644 index 0000000000..7dfdc2d897 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-02/src/main.rs @@ -0,0 +1,21 @@ +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + + stream.read(&mut buffer).unwrap(); + + println!("Request: {}", String::from_utf8_lossy(&buffer[..])); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-03/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-03/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-03/src/main.rs new file mode 100644 index 0000000000..33f4fb732d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-03/src/main.rs @@ -0,0 +1,26 @@ +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + + stream.read(&mut buffer).unwrap(); + + let response = "HTTP/1.1 200 OK\r\n\r\n"; + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-04/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-04/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-04/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-04/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-04/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-04/src/main.rs new file mode 100644 index 0000000000..22e5d1da2d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-04/src/main.rs @@ -0,0 +1,24 @@ +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + + stream.read(&mut buffer).unwrap(); + + let response = "HTTP/1.1 200 OK\r\n\r\n"; + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-05/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-05/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs new file mode 100644 index 0000000000..0b3a284a77 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs @@ -0,0 +1,32 @@ +// ANCHOR: here +use std::fs; +// --snip-- + +// ANCHOR_END: here +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-06/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-06/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-06/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs new file mode 100644 index 0000000000..dc192d76bd --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs @@ -0,0 +1,36 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +// --snip-- + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + if buffer.starts_with(get) { + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } else { + // some other request + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-07/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-07/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-07/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-07/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-07/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-07/src/main.rs new file mode 100644 index 0000000000..9fab0c76be --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-07/src/main.rs @@ -0,0 +1,41 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + if buffer.starts_with(get) { + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + // ANCHOR: here + // --snip-- + } else { + let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n"; + let contents = fs::read_to_string("404.html").unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } + // ANCHOR_END: here +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-08/404.html b/src/doc/book/listings/ch20-web-server/listing-20-08/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-08/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-08/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-08/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-08/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-08/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-08/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-08/src/main.rs new file mode 100644 index 0000000000..cbcc4c01ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-08/src/main.rs @@ -0,0 +1,38 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + if buffer.starts_with(get) { + let contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } else { + let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n"; + let contents = fs::read_to_string("404.html").unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + } +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-09/404.html b/src/doc/book/listings/ch20-web-server/listing-20-09/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-09/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-09/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-09/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-09/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-09/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-09/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-09/src/main.rs new file mode 100644 index 0000000000..c91bb660df --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-09/src/main.rs @@ -0,0 +1,42 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +// ANCHOR: here +// --snip-- + +fn handle_connection(mut stream: TcpStream) { + // --snip-- + + // ANCHOR_END: here + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + + // ANCHOR: here + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-10/404.html b/src/doc/book/listings/ch20-web-server/listing-20-10/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-10/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-10/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-10/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-10/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-10/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-10/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-10/src/main.rs new file mode 100644 index 0000000000..6ea692fcb3 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-10/src/main.rs @@ -0,0 +1,53 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +// ANCHOR: here +use std::thread; +use std::time::Duration; +// --snip-- +// ANCHOR_END: here + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} +// ANCHOR: here + +fn handle_connection(mut stream: TcpStream) { + // --snip-- + + // ANCHOR_END: here + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + // ANCHOR: here + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + // --snip-- + // ANCHOR_END: here + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-11/404.html b/src/doc/book/listings/ch20-web-server/listing-20-11/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-11/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-11/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-11/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-11/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-11/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-11/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-11/src/main.rs new file mode 100644 index 0000000000..7eb3372ba6 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-11/src/main.rs @@ -0,0 +1,44 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + thread::spawn(|| { + handle_connection(stream); + }); + } +} +// ANCHOR_END: here + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-12/404.html b/src/doc/book/listings/ch20-web-server/listing-20-12/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-12/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-12/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-12/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-12/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-12/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-12/output.txt b/src/doc/book/listings/ch20-web-server/listing-20-12/output.txt new file mode 100644 index 0000000000..3a798ef120 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-12/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0433]: failed to resolve: use of undeclared type or module `ThreadPool` + --> src/main.rs:10:16 + | +10 | let pool = ThreadPool::new(4); + | ^^^^^^^^^^ use of undeclared type or module `ThreadPool` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0433`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch20-web-server/listing-20-12/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-12/src/main.rs new file mode 100644 index 0000000000..1381e6d6d2 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-12/src/main.rs @@ -0,0 +1,45 @@ +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} +// ANCHOR_END: here + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-13/404.html b/src/doc/book/listings/ch20-web-server/listing-20-13/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-13/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-13/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-13/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-13/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-13/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-13/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-13/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-13/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-13/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-13/src/lib.rs new file mode 100644 index 0000000000..ffa3c6a254 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-13/src/lib.rs @@ -0,0 +1,30 @@ +pub struct ThreadPool; + +// ANCHOR: here +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + ThreadPool + } + + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-14/404.html b/src/doc/book/listings/ch20-web-server/listing-20-14/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-14/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-14/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-14/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-14/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-14/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-14/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-14/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-14/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-14/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-14/src/lib.rs new file mode 100644 index 0000000000..509a62e1f9 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-14/src/lib.rs @@ -0,0 +1,41 @@ +// ANCHOR: here +use std::thread; + +pub struct ThreadPool { + threads: Vec>, +} + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let mut threads = Vec::with_capacity(size); + + for _ in 0..size { + // create some threads and store them in the vector + } + + ThreadPool { threads } + } + + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-15/404.html b/src/doc/book/listings/ch20-web-server/listing-20-15/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-15/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-15/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-15/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-15/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-15/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-15/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-15/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-15/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-15/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-15/src/lib.rs new file mode 100644 index 0000000000..d2ad3ca176 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-15/src/lib.rs @@ -0,0 +1,55 @@ +// ANCHOR: here +use std::thread; + +pub struct ThreadPool { + workers: Vec, +} + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id)); + } + + ThreadPool { workers } + } + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize) -> Worker { + let thread = thread::spawn(|| {}); + + Worker { id, thread } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-16/404.html b/src/doc/book/listings/ch20-web-server/listing-20-16/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-16/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-16/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-16/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-16/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-16/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-16/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-16/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-16/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-16/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-16/src/lib.rs new file mode 100644 index 0000000000..28b374eed3 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-16/src/lib.rs @@ -0,0 +1,62 @@ +use std::thread; +// ANCHOR: here +// --snip-- +use std::sync::mpsc; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +struct Job; + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id)); + } + + ThreadPool { workers, sender } + } + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize) -> Worker { + let thread = thread::spawn(|| {}); + + Worker { id, thread } + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/404.html b/src/doc/book/listings/ch20-web-server/listing-20-17/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-17/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/output.txt b/src/doc/book/listings/ch20-web-server/listing-20-17/output.txt new file mode 100644 index 0000000000..f9749e1214 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/output.txt @@ -0,0 +1,17 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0382]: use of moved value: `receiver` + --> src/lib.rs:27:42 + | +22 | let (sender, receiver) = mpsc::channel(); + | -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver`, which does not implement the `Copy` trait +... +27 | workers.push(Worker::new(id, receiver)); + | ^^^^^^^^ value moved here, in previous iteration of loop + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-17/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-17/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-17/src/lib.rs new file mode 100644 index 0000000000..f3ce7d06e6 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-17/src/lib.rs @@ -0,0 +1,66 @@ +use std::sync::mpsc; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +struct Job; + +// ANCHOR: here +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, receiver)); + } + + ThreadPool { workers, sender } + } + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} + +// --snip-- + +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: mpsc::Receiver) -> Worker { + let thread = thread::spawn(|| { + receiver; + }); + + Worker { id, thread } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-18/404.html b/src/doc/book/listings/ch20-web-server/listing-20-18/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-18/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-18/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-18/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-18/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-18/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-18/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-18/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-18/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-18/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-18/src/lib.rs new file mode 100644 index 0000000000..d47eef869e --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-18/src/lib.rs @@ -0,0 +1,78 @@ +use std::sync::mpsc; +use std::thread; +// ANCHOR: here +use std::sync::Arc; +use std::sync::Mutex; +// --snip-- + +// ANCHOR_END: here +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +struct Job; + +// ANCHOR: here +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + // ANCHOR: here + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + // --snip-- + // ANCHOR_END: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } + // ANCHOR: here +} + +// --snip-- + +// ANCHOR_END: here +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + // --snip-- + // ANCHOR_END: here + let thread = thread::spawn(|| { + receiver; + }); + + Worker { id, thread } + // ANCHOR: here + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-19/404.html b/src/doc/book/listings/ch20-web-server/listing-20-19/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-19/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-19/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-19/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-19/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-19/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-19/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-19/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-19/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-19/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-19/src/lib.rs new file mode 100644 index 0000000000..bf8127b8e5 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-19/src/lib.rs @@ -0,0 +1,71 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +// ANCHOR: here +// --snip-- + +type Job = Box; + +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + // ANCHOR: here + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +// --snip-- +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(|| { + receiver; + }); + + Worker { id, thread } + } +} + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-20/404.html b/src/doc/book/listings/ch20-web-server/listing-20-20/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-20/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-20/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-20/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-20/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-20/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-20/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-20/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-20/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-20/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-20/src/lib.rs new file mode 100644 index 0000000000..5fdc32e8b0 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-20/src/lib.rs @@ -0,0 +1,68 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +// ANCHOR: here +// --snip-- + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { id, thread } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-21/404.html b/src/doc/book/listings/ch20-web-server/listing-20-21/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-21/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-21/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-21/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-21/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-21/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-21/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-21/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-21/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-21/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-21/src/lib.rs new file mode 100644 index 0000000000..6bde524885 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-21/src/lib.rs @@ -0,0 +1,67 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} +// ANCHOR: here +// --snip-- + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || { + while let Ok(job) = receiver.lock().unwrap().recv() { + println!("Worker {} got a job; executing.", id); + + job(); + } + }); + + Worker { id, thread } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/404.html b/src/doc/book/listings/ch20-web-server/listing-20-22/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-22/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt b/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt new file mode 100644 index 0000000000..f5dd1ba13b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference + --> src/lib.rs:52:13 + | +52 | worker.thread.join().unwrap(); + | ^^^^^^^^^^^^^ move occurs because `worker.thread` has type `std::thread::JoinHandle<()>`, which does not implement the `Copy` trait + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0507`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-22/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-22/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-22/src/lib.rs new file mode 100644 index 0000000000..824257898c --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-22/src/lib.rs @@ -0,0 +1,76 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +// ANCHOR: here +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { id, thread } + } +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-23/404.html b/src/doc/book/listings/ch20-web-server/listing-20-23/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-23/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-23/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-23/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-23/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-23/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-23/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-23/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-23/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-23/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-23/src/lib.rs new file mode 100644 index 0000000000..6ccaee73f6 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-23/src/lib.rs @@ -0,0 +1,107 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +// ANCHOR: here +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +// --snip-- + +// ANCHOR_END: here +type Job = Box; + +enum Message { + NewJob(Job), + Terminate, +} + +// ANCHOR: here +impl ThreadPool { + // --snip-- + + // ANCHOR_END: here + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + // ANCHOR: here + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(Message::NewJob(job)).unwrap(); + } +} + +// --snip-- + +// ANCHOR_END: here +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("Worker {} got a job; executing.", id); + + job(); + } + Message::Terminate => { + println!("Worker {} was told to terminate.", id); + + break; + } + } + }); + + Worker { + id, + thread: Some(thread), + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/listing-20-24/404.html b/src/doc/book/listings/ch20-web-server/listing-20-24/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-24/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-24/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-24/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-24/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-24/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-24/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-24/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-24/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-24/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-24/src/lib.rs new file mode 100644 index 0000000000..747bff2b1f --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-24/src/lib.rs @@ -0,0 +1,103 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +enum Message { + NewJob(Job), + Terminate, +} + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(Message::NewJob(job)).unwrap(); + } +} + +// ANCHOR: here +impl Drop for ThreadPool { + fn drop(&mut self) { + println!("Sending terminate message to all workers."); + + for _ in &self.workers { + self.sender.send(Message::Terminate).unwrap(); + } + + println!("Shutting down all workers."); + + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("Worker {} got a job; executing.", id); + + job(); + } + Message::Terminate => { + println!("Worker {} was told to terminate.", id); + + break; + } + } + }); + + Worker { + id, + thread: Some(thread), + } + } +} diff --git a/src/doc/book/listings/ch20-web-server/listing-20-25/404.html b/src/doc/book/listings/ch20-web-server/listing-20-25/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-25/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-25/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/listing-20-25/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-25/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-25/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/listing-20-25/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-25/src/bin/main.rs new file mode 100644 index 0000000000..8d9310eaec --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-25/src/bin/main.rs @@ -0,0 +1,50 @@ +// ANCHOR: all +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +// ANCHOR: here +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming().take(2) { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + + println!("Shutting down."); +} +// ANCHOR_END: here + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} +// ANCHOR_END: all diff --git a/src/doc/book/listings/ch20-web-server/listing-20-25/src/lib.rs b/src/doc/book/listings/ch20-web-server/listing-20-25/src/lib.rs new file mode 100644 index 0000000000..424eac8e49 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/listing-20-25/src/lib.rs @@ -0,0 +1,105 @@ +// ANCHOR: here +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +enum Message { + NewJob(Job), + Terminate, +} + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(Message::NewJob(job)).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + println!("Sending terminate message to all workers."); + + for _ in &self.workers { + self.sender.send(Message::Terminate).unwrap(); + } + + println!("Shutting down all workers."); + + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("Worker {} got a job; executing.", id); + + job(); + } + Message::Terminate => { + println!("Worker {} was told to terminate.", id); + + break; + } + } + }); + + Worker { + id, + thread: Some(thread), + } + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt new file mode 100644 index 0000000000..0161c7b2c7 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0599]: no function or associated item named `new` found for type `hello::ThreadPool` in the current scope + --> src/bin/main.rs:11:28 + | +11 | let pool = ThreadPool::new(4); + | ^^^ function or associated item not found in `hello::ThreadPool` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0599`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs new file mode 100644 index 0000000000..d4e0e0c0e0 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs @@ -0,0 +1,46 @@ +// ANCHOR: here +use hello::ThreadPool; +// ANCHOR_END: here +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs new file mode 100644 index 0000000000..7312e293d8 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs @@ -0,0 +1 @@ +pub struct ThreadPool; diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt new file mode 100644 index 0000000000..c808b8986b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt @@ -0,0 +1,14 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0599]: no method named `execute` found for type `hello::ThreadPool` in the current scope + --> src/bin/main.rs:16:14 + | +16 | pool.execute(|| { + | ^^^^^^^ method not found in `hello::ThreadPool` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0599`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs new file mode 100644 index 0000000000..3ff5ad4979 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs @@ -0,0 +1,11 @@ +// ANCHOR: here +pub struct ThreadPool; + +impl ThreadPool { + pub fn new(size: usize) -> ThreadPool { + ThreadPool + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/404.html b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/output.txt b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/output.txt new file mode 100644 index 0000000000..dc76c43d6f --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/output.txt @@ -0,0 +1,3 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) + Finished dev [unoptimized + debuginfo] target(s) in 0.24s diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs new file mode 100644 index 0000000000..44e0ebd724 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs @@ -0,0 +1,20 @@ +pub struct ThreadPool; + +// ANCHOR: here +impl ThreadPool { + // --snip-- + // ANCHOR_END: here + pub fn new(size: usize) -> ThreadPool { + ThreadPool + } + + // ANCHOR: here + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + } +} +// ANCHOR_END: here + +fn main() {} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt new file mode 100644 index 0000000000..91907cf79a --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt @@ -0,0 +1,27 @@ +$ cargo check + Checking hello v0.1.0 (file:///projects/hello) +error[E0599]: no method named `join` found for type `std::option::Option>` in the current scope + --> src/lib.rs:52:27 + | +52 | worker.thread.join().unwrap(); + | ^^^^ method not found in `std::option::Option>` + +error[E0308]: mismatched types + --> src/lib.rs:72:22 + | +72 | Worker { id, thread } + | ^^^^^^ + | | + | expected enum `std::option::Option`, found struct `std::thread::JoinHandle` + | help: try using a variant of the expected enum: `Some(thread)` + | + = note: expected enum `std::option::Option>` + found struct `std::thread::JoinHandle<_>` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0308, E0599. +For more information about an error, try `rustc --explain E0308`. +error: could not compile `hello`. + +To learn more, run the command again with --verbose. diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs new file mode 100644 index 0000000000..1098330b3f --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs @@ -0,0 +1,76 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} + +// ANCHOR: here +struct Worker { + id: usize, + thread: Option>, +} +// ANCHOR_END: here + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { id, thread } + } +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs new file mode 100644 index 0000000000..6bef23a16d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs @@ -0,0 +1,83 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +// ANCHOR: here +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + // --snip-- + + // ANCHOR_END: here + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + // ANCHOR: here + Worker { + id, + thread: Some(thread), + } + } +} +// ANCHOR_END: here diff --git a/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs new file mode 100644 index 0000000000..d5b38a635d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs @@ -0,0 +1,81 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +// ANCHOR: here +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} +// ANCHOR_END: here + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { + id, + thread: Some(thread), + } + } +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/404.html b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/404.html new file mode 100644 index 0000000000..88d8e9152d --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Oops!

+

Sorry, I don't know what you're asking for.

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock new file mode 100644 index 0000000000..f2d069f462 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "hello" +version = "0.1.0" + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml new file mode 100644 index 0000000000..78dfe6ebc4 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello" +version = "0.1.0" +authors = ["Your Name "] +edition = "2018" + +[dependencies] diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html new file mode 100644 index 0000000000..fe442d6b9b --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs new file mode 100644 index 0000000000..452f6822ff --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/bin/main.rs @@ -0,0 +1,44 @@ +use hello::ThreadPool; +use std::fs; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; +use std::thread; +use std::time::Duration; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::new(4); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 512]; + stream.read(&mut buffer).unwrap(); + + let get = b"GET / HTTP/1.1\r\n"; + let sleep = b"GET /sleep HTTP/1.1\r\n"; + + let (status_line, filename) = if buffer.starts_with(get) { + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else if buffer.starts_with(sleep) { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") + } else { + ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + + let response = format!("{}{}", status_line, contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} diff --git a/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs new file mode 100644 index 0000000000..ed1913b293 --- /dev/null +++ b/src/doc/book/listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs @@ -0,0 +1,88 @@ +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; + +pub struct ThreadPool { + workers: Vec, + sender: mpsc::Sender, +} + +type Job = Box; + +// ANCHOR: here +enum Message { + NewJob(Job), + Terminate, +} +// ANCHOR_END: here + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The `new` function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { workers, sender } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for worker in &mut self.workers { + println!("Shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + let thread = thread::spawn(move || loop { + let job = receiver.lock().unwrap().recv().unwrap(); + + println!("Worker {} got a job; executing.", id); + + job(); + }); + + Worker { + id, + thread: Some(thread), + } + } +} + +fn main() {} diff --git a/src/doc/book/rust-toolchain b/src/doc/book/rust-toolchain index bf50e910e6..7d47e59980 100644 --- a/src/doc/book/rust-toolchain +++ b/src/doc/book/rust-toolchain @@ -1 +1 @@ -1.37.0 +1.41.0 diff --git a/src/doc/book/rustfmt.toml b/src/doc/book/rustfmt.toml new file mode 100644 index 0000000000..df99c69198 --- /dev/null +++ b/src/doc/book/rustfmt.toml @@ -0,0 +1 @@ +max_width = 80 diff --git a/src/doc/book/second-edition/src/ch18-02-refutability.md b/src/doc/book/second-edition/src/ch18-02-refutability.md index 7449d2f39f..2ef5206afd 100644 --- a/src/doc/book/second-edition/src/ch18-02-refutability.md +++ b/src/doc/book/second-edition/src/ch18-02-refutability.md @@ -7,4 +7,4 @@ version of the book](../ch18-02-refutability.html) instead. If you have an internet connection, you can [find a copy distributed with Rust -1.30](https://doc.rust-lang.org/1.30.0/book/second-edition/ch18-02-refuatbility.html). \ No newline at end of file +1.30](https://doc.rust-lang.org/1.30.0/book/second-edition/ch18-02-refutability.html). \ No newline at end of file diff --git a/src/doc/book/src/appendix-01-keywords.md b/src/doc/book/src/appendix-01-keywords.md index ef1c51d571..c19b8a1e2f 100644 --- a/src/doc/book/src/appendix-01-keywords.md +++ b/src/doc/book/src/appendix-01-keywords.md @@ -42,7 +42,7 @@ The following keywords currently have the functionality described. * `pub` - denote public visibility in struct fields, `impl` blocks, or modules * `ref` - bind by reference * `return` - return from function -* `Self` - a type alias for the type implementing a trait +* `Self` - a type alias for the type we are defining or implementing * `self` - method subject or current module * `static` - global variable or lifetime lasting the entire program execution * `struct` - define a structure diff --git a/src/doc/book/src/appendix-02-operators.md b/src/doc/book/src/appendix-02-operators.md index 3bddf322df..e70cc737f5 100644 --- a/src/doc/book/src/appendix-02-operators.md +++ b/src/doc/book/src/appendix-02-operators.md @@ -153,6 +153,7 @@ macros and specifying attributes on an item. | `$ident` | Macro substitution | | `$ident:kind` | Macro capture | | `$(…)…` | Macro repetition | +| `ident!(...)`, `ident!{...}`, `ident![...]` | Macro invocation | Table B-7 shows symbols that create comments. @@ -180,7 +181,6 @@ Table B-8 shows symbols that appear in the context of using tuples. | `(expr, ...)` | Tuple expression | | `(type, ...)` | Tuple type | | `expr(expr, ...)` | Function call expression; also used to initialize tuple `struct`s and tuple `enum` variants | -| `ident!(...)`, `ident!{...}`, `ident![...]` | Macro invocation | | `expr.0`, `expr.1`, etc. | Tuple indexing | Table B-9 shows the contexts in which curly braces are used. diff --git a/src/doc/book/src/appendix-06-translation.md b/src/doc/book/src/appendix-06-translation.md index 937928bf44..8193f51e60 100644 --- a/src/doc/book/src/appendix-06-translation.md +++ b/src/doc/book/src/appendix-06-translation.md @@ -13,8 +13,8 @@ For resources in languages other than English. Most are still in progress; see - [Italiano](https://github.com/AgeOfWar/rust-book-it) - [Русский](https://github.com/ruRust/rust_book_2ed) - [한국어](https://github.com/rinthel/rust-lang-book-ko) -- [日本語](https://github.com/hazama-yuinyan/book) -- [Français](https://github.com/quadrifoglio/rust-book-fr) +- [日本語](https://github.com/rust-lang-ja/book-ja) +- [Français](https://github.com/Jimskapt/rust-book-fr) - [Polski](https://github.com/paytchoo/book-pl) - [עברית](https://github.com/idanmel/rust-book-heb) - [Cebuano](https://github.com/agentzero1/book) diff --git a/src/doc/book/src/appendix-07-nightly-rust.md b/src/doc/book/src/appendix-07-nightly-rust.md index bace82f2e0..ac8609167f 100644 --- a/src/doc/book/src/appendix-07-nightly-rust.md +++ b/src/doc/book/src/appendix-07-nightly-rust.md @@ -142,7 +142,7 @@ global or per-project basis. By default, you’ll have stable Rust installed. To install nightly, for example: ```text -$ rustup install nightly +$ rustup toolchain install nightly ``` You can see all of the *toolchains* (releases of Rust and associated diff --git a/src/doc/book/src/ch01-03-hello-cargo.md b/src/doc/book/src/ch01-03-hello-cargo.md index b40be39da5..fe029d9a16 100644 --- a/src/doc/book/src/ch01-03-hello-cargo.md +++ b/src/doc/book/src/ch01-03-hello-cargo.md @@ -44,8 +44,11 @@ same name. Go into the *hello_cargo* directory and list the files. You’ll see that Cargo has generated two files and one directory for us: a *Cargo.toml* file and a -*src* directory with a *main.rs* file inside. It has also initialized a new Git -repository along with a *.gitignore* file. +*src* directory with a *main.rs* file inside. + +It has also initialized a new Git repository along with a *.gitignore* file. +Git files won’t be generated if you run `cargo new` within an existing Git +repository; you can override this behavior by using `cargo new --vcs=git`. > Note: Git is a common version control system. You can change `cargo new` to > use a different version control system or no version control system by using diff --git a/src/doc/book/src/ch02-00-guessing-game-tutorial.md b/src/doc/book/src/ch02-00-guessing-game-tutorial.md index 2ecc1520ea..b09dade72f 100644 --- a/src/doc/book/src/ch02-00-guessing-game-tutorial.md +++ b/src/doc/book/src/ch02-00-guessing-game-tutorial.md @@ -31,13 +31,7 @@ Look at the generated *Cargo.toml* file: Filename: Cargo.toml ```toml -[package] -name = "guessing_game" -version = "0.1.0" -authors = ["Your Name "] -edition = "2018" - -[dependencies] +{{#include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml}} ``` If the author information that Cargo obtained from your environment is not @@ -49,20 +43,14 @@ you. Check out the *src/main.rs* file: Filename: src/main.rs ```rust -fn main() { - println!("Hello, world!"); -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs}} ``` Now let’s compile this “Hello, world!” program and run it in the same step using the `cargo run` command: ```text -$ cargo run - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 1.50 secs - Running `target/debug/guessing_game` -Hello, world! +{{#include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt}} ``` The `run` command comes in handy when you need to rapidly iterate on a project, @@ -81,20 +69,7 @@ allow the player to input a guess. Enter the code in Listing 2-1 into Filename: src/main.rs ```rust,ignore -use std::io; - -fn main() { - println!("Guess the number!"); - - println!("Please input your guess."); - - let mut guess = String::new(); - - io::stdin().read_line(&mut guess) - .expect("Failed to read line"); - - println!("You guessed: {}", guess); -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:all}} ``` Listing 2-1: Code that gets a guess from the user and @@ -106,7 +81,7 @@ obtain user input and then print the result as output, we need to bring the standard library (which is known as `std`): ```rust,ignore -use std::io; +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:io}} ``` By default, Rust brings only a few types into the scope of every program in @@ -121,7 +96,7 @@ As you saw in Chapter 1, the `main` function is the entry point into the program: ```rust,ignore -fn main() { +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:main}} ``` The `fn` syntax declares a new function, the parentheses, `()`, indicate there @@ -131,9 +106,7 @@ As you also learned in Chapter 1, `println!` is a macro that prints a string to the screen: ```rust,ignore -println!("Guess the number!"); - -println!("Please input your guess."); +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:print}} ``` This code is printing a prompt stating what the game is and requesting input @@ -144,7 +117,7 @@ from the user. Next, we’ll create a place to store the user input, like this: ```rust,ignore -let mut guess = String::new(); +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:string}} ``` Now the program is getting interesting! There’s a lot going on in this little @@ -197,8 +170,7 @@ library with `use std::io;` on the first line of the program. Now we’ll call the `stdin` function from the `io` module: ```rust,ignore -io::stdin().read_line(&mut guess) - .expect("Failed to read line"); +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:read}} ``` If we hadn’t put the `use std::io` line at the beginning of the program, we @@ -232,12 +204,12 @@ thoroughly.) ### Handling Potential Failure with the `Result` Type -We’re not quite done with this line of code. Although what we’ve discussed so -far is a single line of text, it’s only the first part of the single logical -line of code. The second part is this method: +We’re still working on this line of code. Although we’re now discussing a third +line of text, it’s still part of a single logical line of code. The next part +is this method: ```rust,ignore -.expect("Failed to read line"); +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:expect}} ``` When you call a method with the `.foo()` syntax, it’s often wise to introduce a @@ -248,8 +220,8 @@ written this code as: io::stdin().read_line(&mut guess).expect("Failed to read line"); ``` -However, one long line is difficult to read, so it’s best to divide it: two -lines for two method calls. Now let’s discuss what this line does. +However, one long line is difficult to read, so it’s best to divide it. Now +let’s discuss what this line does. As mentioned earlier, `read_line` puts what the user types into the string we’re passing it, but it also returns a value—in this case, an @@ -289,15 +261,7 @@ entered into standard input. If you don’t call `expect`, the program will compile, but you’ll get a warning: ```text -$ cargo build - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) -warning: unused `std::result::Result` which must be used - --> src/main.rs:10:5 - | -10 | io::stdin().read_line(&mut guess); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: #[warn(unused_must_use)] on by default +{{#include ../listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt}} ``` Rust warns that you haven’t used the `Result` value returned from `read_line`, @@ -309,11 +273,11 @@ because you just want to crash this program when a problem occurs, you can use ### Printing Values with `println!` Placeholders -Aside from the closing curly brackets, there’s only one more line to discuss in +Aside from the closing curly bracket, there’s only one more line to discuss in the code added so far, which is the following: ```rust,ignore -println!("You guessed: {}", guess); +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:print_guess}} ``` This line prints the string we saved the user’s input in. The set of curly @@ -336,10 +300,16 @@ This code would print `x = 5 and y = 10`. Let’s test the first part of the guessing game. Run it using `cargo run`: + + ```text $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs + Finished dev [unoptimized + debuginfo] target(s) in 6.44s Running `target/debug/guessing_game` Guess the number! Please input your guess. @@ -382,8 +352,7 @@ you: Filename: Cargo.toml ```toml -[dependencies] -rand = "0.5.5" +{{#include ../listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml:9:}} ``` In the *Cargo.toml* file, everything that follows a header is part of a section @@ -401,6 +370,11 @@ version 0.5.5.” Now, without changing any of the code, let’s build the project, as shown in Listing 2-2. + + ```text $ cargo build Updating crates.io index @@ -415,7 +389,7 @@ $ cargo build Compiling rand_core v0.2.2 Compiling rand v0.5.5 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 s + Finished dev [unoptimized + debuginfo] target(s) in 2.53s ``` Listing 2-2: The output from running `cargo build` after @@ -433,9 +407,9 @@ their open source Rust projects for others to use. After updating the registry, Cargo checks the `[dependencies]` section and downloads any crates you don’t have yet. In this case, although we only listed -`rand` as a dependency, Cargo also grabbed `libc` and `rand_core`, because `rand` -depends on those to work. After downloading the crates, Rust compiles them and -then compiles the project with the dependencies available. +`rand` as a dependency, Cargo also grabbed `libc` and `rand_core`, because +`rand` depends on those to work. After downloading the crates, Rust compiles +them and then compiles the project with the dependencies available. If you immediately run `cargo build` again without making any changes, you won’t get any output aside from the `Finished` line. Cargo knows it has already @@ -447,10 +421,15 @@ do, it simply exits. If you open up the *src/main.rs* file, make a trivial change, and then save it and build again, you’ll only see two lines of output: + + ```text $ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53s + Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs ``` These lines show Cargo only updates the build with your tiny change to the @@ -489,6 +468,12 @@ But by default, Cargo will only look for versions greater than `0.5.5` and less than `0.6.0`. If the `rand` crate has released two new versions, `0.5.6` and `0.6.0`, you would see the following if you ran `cargo update`: + + ```text $ cargo update Updating crates.io index @@ -527,25 +512,7 @@ Now that you’ve added the `rand` crate to *Cargo.toml*, let’s start using Filename: src/main.rs ```rust,ignore -use std::io; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let mut guess = String::new(); - - io::stdin().read_line(&mut guess) - .expect("Failed to read line"); - - println!("You guessed: {}", guess); -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs:all}} ``` Listing 2-3: Adding code to generate a random @@ -580,17 +547,27 @@ program prints the answer as soon as it starts! Try running the program a few times: + + ```text $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs + Finished dev [unoptimized + debuginfo] target(s) in 2.53s Running `target/debug/guessing_game` Guess the number! The secret number is: 7 Please input your guess. 4 You guessed: 4 + $ cargo run + Finished dev [unoptimized + debuginfo] target(s) in 0.02s Running `target/debug/guessing_game` Guess the number! The secret number is: 83 @@ -611,22 +588,7 @@ will explain. Filename: src/main.rs ```rust,ignore,does_not_compile -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - - // ---snip--- - - println!("You guessed: {}", guess); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-04/src/main.rs:here}} ``` Listing 2-4: Handling the possible return values of @@ -672,19 +634,7 @@ expression ends because it has no need to look at the last arm in this scenario. However, the code in Listing 2-4 won’t compile yet. Let’s try it: ```text -$ cargo build - Compiling guessing_game v0.1.0 (file:///projects/guessing_game) -error[E0308]: mismatched types - --> src/main.rs:23:21 - | -23 | match guess.cmp(&secret_number) { - | ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integer - | - = note: expected type `&std::string::String` - = note: found type `&{integer}` - -error: aborting due to previous error -Could not compile `guessing_game`. +{{#include ../listings/ch02-guessing-game-tutorial/listing-02-04/output.txt}} ``` The core of the error states that there are *mismatched types*. Rust has a @@ -705,24 +655,7 @@ do that by adding the following two lines to the `main` function body: Filename: src/main.rs ```rust,ignore -// --snip-- - - let mut guess = String::new(); - - io::stdin().read_line(&mut guess) - .expect("Failed to read line"); - - let guess: u32 = guess.trim().parse() - .expect("Please type a number!"); - - println!("You guessed: {}", guess); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-03-convert-string-to-number/src/main.rs:here}} ``` The two new lines are: @@ -779,10 +712,16 @@ number that we want from the `Ok` value. Let’s run the program now! + + ```text $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 0.43 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/guessing_game` Guess the number! The secret number is: 58 @@ -808,22 +747,7 @@ more chances at guessing the number: Filename: src/main.rs ```rust,ignore -// --snip-- - - println!("The secret number is: {}", secret_number); - - loop { - println!("Please input your guess."); - - // --snip-- - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } - } -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-04-looping/src/main.rs:here}} ``` As you can see, we’ve moved everything into a loop from the guess input prompt @@ -839,10 +763,19 @@ Guess to the Secret Number”](#comparing-the-guess-to-the-secret-number): if the user enters a non-number answer, the program will crash. The user can take advantage of that in order to quit, as shown here: + + ```text $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) - Finished dev [unoptimized + debuginfo] target(s) in 1.50 secs + Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Guess the number! The secret number is: 59 @@ -860,9 +793,8 @@ You guessed: 59 You win! Please input your guess. quit -thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -error: Process didn't exit successfully: `target/debug/guess` (exit code: 101) +thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:999:5 +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. ``` Typing `quit` actually quits the game, but so will any other non-number input. @@ -876,18 +808,7 @@ Let’s program the game to quit when the user wins by adding a `break` statemen Filename: src/main.rs ```rust,ignore -// --snip-- - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - break; - } - } - } -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-05-quitting/src/main.rs:here}} ``` Adding the `break` line after `You win!` makes the program exit the loop when @@ -904,19 +825,7 @@ is converted from a `String` to a `u32`, as shown in Listing 2-5. Filename: src/main.rs ```rust,ignore -// --snip-- - -io::stdin().read_line(&mut guess) - .expect("Failed to read line"); - -let guess: u32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, -}; - -println!("You guessed: {}", guess); - -// --snip-- +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs:here}} ``` Listing 2-5: Ignoring a non-number guess and asking for @@ -946,6 +855,15 @@ program ignores all errors that `parse` might encounter! Now everything in the program should work as expected. Let’s try it: + + ```text $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) @@ -976,40 +894,7 @@ secret number. Listing 2-6 shows the final code. Filename: src/main.rs ```rust,ignore -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - loop { - println!("Please input your guess."); - - let mut guess = String::new(); - - io::stdin().read_line(&mut guess) - .expect("Failed to read line"); - - let guess: u32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, - }; - - println!("You guessed: {}", guess); - - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - break; - } - } - } -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-06/src/main.rs}} ``` Listing 2-6: Complete guessing game code diff --git a/src/doc/book/src/ch03-00-common-programming-concepts.md b/src/doc/book/src/ch03-00-common-programming-concepts.md index 4b91c2a5cf..801ecc3c34 100644 --- a/src/doc/book/src/ch03-00-common-programming-concepts.md +++ b/src/doc/book/src/ch03-00-common-programming-concepts.md @@ -18,4 +18,6 @@ them early will give you a strong core to start from. > special meanings, and you’ll be using them to do various tasks in your Rust > programs; a few have no current functionality associated with them but have > been reserved for functionality that might be added to Rust in the future. You -> can find a list of the keywords in Appendix A. +> can find a list of the keywords in [Appendix A][appendix_a]. + +[appendix_a]: appendix-01-keywords.md diff --git a/src/doc/book/src/ch03-01-variables-and-mutability.md b/src/doc/book/src/ch03-01-variables-and-mutability.md index d6a73a092e..05fea9aa2b 100644 --- a/src/doc/book/src/ch03-01-variables-and-mutability.md +++ b/src/doc/book/src/ch03-01-variables-and-mutability.md @@ -17,26 +17,14 @@ code with the following code that won’t compile just yet: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let x = 5; - println!("The value of x is: {}", x); - x = 6; - println!("The value of x is: {}", x); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/src/main.rs}} ``` Save and run the program using `cargo run`. You should receive an error message, as shown in this output: ```text -error[E0384]: cannot assign twice to immutable variable `x` - --> src/main.rs:4:5 - | -2 | let x = 5; - | - first assignment to `x` -3 | println!("The value of x is: {}", x); -4 | x = 6; - | ^^^^^ cannot assign twice to immutable variable +{{#include ../listings/ch03-common-programming-concepts/no-listing-01-variables-are-immutable/output.txt}} ``` This example shows how the compiler helps you find errors in your programs. @@ -72,23 +60,13 @@ For example, let’s change *src/main.rs* to the following: Filename: src/main.rs ```rust -fn main() { - let mut x = 5; - println!("The value of x is: {}", x); - x = 6; - println!("The value of x is: {}", x); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-02-adding-mut/src/main.rs}} ``` When we run the program now, we get this: ```text -$ cargo run - Compiling variables v0.1.0 (file:///projects/variables) - Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs - Running `target/debug/variables` -The value of x is: 5 -The value of x is: 6 +{{#include ../listings/ch03-common-programming-concepts/no-listing-02-adding-mut/output.txt}} ``` We’re allowed to change the value that `x` binds to from `5` to `6` when `mut` @@ -160,15 +138,7 @@ of the `let` keyword as follows: Filename: src/main.rs ```rust -fn main() { - let x = 5; - - let x = x + 1; - - let x = x * 2; - - println!("The value of x is: {}", x); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-03-shadowing/src/main.rs}} ``` This program first binds `x` to a value of `5`. Then it shadows `x` by @@ -178,11 +148,7 @@ previous value by `2` to give `x` a final value of `12`. When we run this program, it will output the following: ```text -$ cargo run - Compiling variables v0.1.0 (file:///projects/variables) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/variables` -The value of x is: 12 +{{#include ../listings/ch03-common-programming-concepts/no-listing-03-shadowing/output.txt}} ``` Shadowing is different from marking a variable as `mut`, because we’ll get a @@ -198,8 +164,7 @@ program asks a user to show how many spaces they want between some text by inputting space characters, but we really want to store that input as a number: ```rust -let spaces = " "; -let spaces = spaces.len(); +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-04-shadowing-can-change-types/src/main.rs:here}} ``` This construct is allowed because the first `spaces` variable is a string type @@ -210,21 +175,13 @@ from having to come up with different names, such as `spaces_str` and try to use `mut` for this, as shown here, we’ll get a compile-time error: ```rust,ignore,does_not_compile -let mut spaces = " "; -spaces = spaces.len(); +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/src/main.rs:here}} ``` The error says we’re not allowed to mutate a variable’s type: ```text -error[E0308]: mismatched types - --> src/main.rs:3:14 - | -3 | spaces = spaces.len(); - | ^^^^^^^^^^^^ expected &str, found usize - | - = note: expected type `&str` - found type `usize` +{{#include ../listings/ch03-common-programming-concepts/no-listing-05-mut-cant-change-types/output.txt}} ``` Now that we’ve explored how variables work, let’s look at more data types they diff --git a/src/doc/book/src/ch03-02-data-types.md b/src/doc/book/src/ch03-02-data-types.md index 482e69f73f..5c8b162b80 100644 --- a/src/doc/book/src/ch03-02-data-types.md +++ b/src/doc/book/src/ch03-02-data-types.md @@ -21,14 +21,7 @@ error, which means the compiler needs more information from us to know which type we want to use: ```text -error[E0282]: type annotations needed - --> src/main.rs:2:9 - | -2 | let guess = "42".parse().expect("Not a number!"); - | ^^^^^ - | | - | cannot infer type for `_` - | consider giving `guess` a type +{{#include ../listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/output.txt}} ``` You’ll see different type annotations for other data types. @@ -133,11 +126,7 @@ Here’s an example that shows floating-point numbers in action: Filename: src/main.rs ```rust -fn main() { - let x = 2.0; // f64 - - let y: f32 = 3.0; // f32 -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-06-floating-point/src/main.rs}} ``` Floating-point numbers are represented according to the IEEE-754 standard. The @@ -152,22 +141,7 @@ The following code shows how you’d use each one in a `let` statement: Filename: src/main.rs ```rust -fn main() { - // addition - let sum = 5 + 10; - - // subtraction - let difference = 95.5 - 4.3; - - // multiplication - let product = 4 * 30; - - // division - let quotient = 56.7 / 32.2; - - // remainder - let remainder = 43 % 5; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-07-numeric-operations/src/main.rs}} ``` Each expression in these statements uses a mathematical operator and evaluates @@ -183,11 +157,7 @@ Rust is specified using `bool`. For example: Filename: src/main.rs ```rust -fn main() { - let t = true; - - let f: bool = false; // with explicit type annotation -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-08-boolean/src/main.rs}} ``` The main way to use Boolean values is through conditionals, such as an `if` @@ -204,11 +174,7 @@ single quotes, as opposed to string literals, which use double quotes.) Filename: src/main.rs ```rust -fn main() { - let c = 'z'; - let z = 'ℤ'; - let heart_eyed_cat = '😻'; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-09-char/src/main.rs}} ``` Rust’s `char` type is four bytes in size and represents a Unicode Scalar Value, @@ -240,9 +206,7 @@ type annotations in this example: Filename: src/main.rs ```rust -fn main() { - let tup: (i32, f64, u8) = (500, 6.4, 1); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-10-tuples/src/main.rs}} ``` The variable `tup` binds to the entire tuple, because a tuple is considered a @@ -252,13 +216,7 @@ use pattern matching to destructure a tuple value, like this: Filename: src/main.rs ```rust -fn main() { - let tup = (500, 6.4, 1); - - let (x, y, z) = tup; - - println!("The value of y is: {}", y); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-11-destructuring-tuples/src/main.rs}} ``` This program first creates a tuple and binds it to the variable `tup`. It then @@ -274,15 +232,7 @@ want to access. For example: Filename: src/main.rs ```rust -fn main() { - let x: (i32, f64, u8) = (500, 6.4, 1); - - let five_hundred = x.0; - - let six_point_four = x.1; - - let one = x.2; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-12-tuple-indexing/src/main.rs}} ``` This program creates a tuple, `x`, and then makes new variables for each @@ -302,9 +252,7 @@ inside square brackets: Filename: src/main.rs ```rust -fn main() { - let a = [1, 2, 3, 4, 5]; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-13-arrays/src/main.rs}} ``` Arrays are useful when you want your data allocated on the stack rather than @@ -357,12 +305,7 @@ elements of an array using indexing, like this: Filename: src/main.rs ```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-14-array-indexing/src/main.rs}} ``` In this example, the variable named `first` will get the value `1`, because @@ -378,26 +321,13 @@ compile but exit with an error when it runs: Filename: src/main.rs ```rust,ignore,panics -fn main() { - let a = [1, 2, 3, 4, 5]; - let index = 10; - - let element = a[index]; - - println!("The value of element is: {}", element); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs}} ``` Running this code using `cargo run` produces the following result: ```text -$ cargo run - Compiling arrays v0.1.0 (file:///projects/arrays) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/arrays` -thread 'main' panicked at 'index out of bounds: the len is 5 but the index is - 10', src/main.rs:5:19 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt}} ``` The compilation didn’t produce any errors, but the program resulted in a diff --git a/src/doc/book/src/ch03-03-how-functions-work.md b/src/doc/book/src/ch03-03-how-functions-work.md index 9500757997..491a69b859 100644 --- a/src/doc/book/src/ch03-03-how-functions-work.md +++ b/src/doc/book/src/ch03-03-how-functions-work.md @@ -12,15 +12,7 @@ Here’s a program that contains an example function definition: Filename: src/main.rs ```rust -fn main() { - println!("Hello, world!"); - - another_function(); -} - -fn another_function() { - println!("Another function."); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-16-functions/src/main.rs}} ``` Function definitions in Rust start with `fn` and have a set of parentheses @@ -39,12 +31,7 @@ further. Place the `another_function` example in *src/main.rs* and run it. You should see the following output: ```text -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 0.28 secs - Running `target/debug/functions` -Hello, world! -Another function. +{{#include ../listings/ch03-common-programming-concepts/no-listing-16-functions/output.txt}} ``` The lines execute in the order in which they appear in the `main` function. @@ -67,23 +54,13 @@ look like in Rust: Filename: src/main.rs ```rust -fn main() { - another_function(5); -} - -fn another_function(x: i32) { - println!("The value of x is: {}", x); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/src/main.rs}} ``` Try running this program; you should get the following output: ```text -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 1.21 secs - Running `target/debug/functions` -The value of x is: 5 +{{#include ../listings/ch03-common-programming-concepts/no-listing-17-functions-with-parameters/output.txt}} ``` The declaration of `another_function` has one parameter named `x`. The type of @@ -102,14 +79,7 @@ declarations with commas, like this: Filename: src/main.rs ```rust -fn main() { - another_function(5, 6); -} - -fn another_function(x: i32, y: i32) { - println!("The value of x is: {}", x); - println!("The value of y is: {}", y); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/src/main.rs}} ``` This example creates a function with two parameters, both of which are `i32` @@ -122,12 +92,7 @@ project’s *src/main.rs* file with the preceding example and run it using `carg run`: ```text -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/functions` -The value of x is: 5 -The value of y is: 6 +{{#include ../listings/ch03-common-programming-concepts/no-listing-18-functions-with-multiple-parameters/output.txt}} ``` Because we called the function with `5` as the value for `x` and `6` is passed @@ -153,9 +118,7 @@ statement. In Listing 3-1, `let y = 6;` is a statement. Filename: src/main.rs ```rust -fn main() { - let y = 6; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-01/src/main.rs}} ``` Listing 3-1: A `main` function declaration containing one statement @@ -169,13 +132,14 @@ to another variable, as the following code tries to do; you’ll get an error: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let x = (let y = 6); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-19-statements-vs-expressions/src/main.rs}} ``` When you run this program, the error you’ll get looks like this: + + ```text $ cargo run Compiling functions v0.1.0 (file:///projects/functions) @@ -205,16 +169,7 @@ new scopes, `{}`, is an expression, for example: Filename: src/main.rs ```rust -fn main() { - let x = 5; - - let y = { - let x = 3; - x + 1 - }; - - println!("The value of y is: {}", y); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-20-blocks-are-expressions/src/main.rs}} ``` This expression: @@ -246,15 +201,7 @@ value: Filename: src/main.rs ```rust -fn five() -> i32 { - 5 -} - -fn main() { - let x = five(); - - println!("The value of x is: {}", x); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-21-function-return-values/src/main.rs}} ``` There are no function calls, macros, or even `let` statements in the `five` @@ -263,11 +210,7 @@ Rust. Note that the function’s return type is specified too, as `-> i32`. Try running this code; the output should look like this: ```text -$ cargo run - Compiling functions v0.1.0 (file:///projects/functions) - Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs - Running `target/debug/functions` -The value of x is: 5 +{{#include ../listings/ch03-common-programming-concepts/no-listing-21-function-return-values/output.txt}} ``` The `5` in `five` is the function’s return value, which is why the return type @@ -289,15 +232,7 @@ Let’s look at another example: Filename: src/main.rs ```rust -fn main() { - let x = plus_one(5); - - println!("The value of x is: {}", x); -} - -fn plus_one(x: i32) -> i32 { - x + 1 -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-22-function-parameter-and-return/src/main.rs}} ``` Running this code will print `The value of x is: 6`. But if we place a @@ -307,32 +242,13 @@ expression to a statement, we’ll get an error. Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let x = plus_one(5); - - println!("The value of x is: {}", x); -} - -fn plus_one(x: i32) -> i32 { - x + 1; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/src/main.rs}} ``` Compiling this code produces an error, as follows: ```text -error[E0308]: mismatched types - --> src/main.rs:7:28 - | -7 | fn plus_one(x: i32) -> i32 { - | ____________________________^ -8 | | x + 1; - | | - help: consider removing this semicolon -9 | | } - | |_^ expected i32, found () - | - = note: expected type `i32` - found type `()` +{{#include ../listings/ch03-common-programming-concepts/no-listing-23-statements-dont-return-values/output.txt}} ``` The main error message, “mismatched types,” reveals the core issue with this diff --git a/src/doc/book/src/ch03-04-comments.md b/src/doc/book/src/ch03-04-comments.md index d42e38c2a2..6a3f8efd46 100644 --- a/src/doc/book/src/ch03-04-comments.md +++ b/src/doc/book/src/ch03-04-comments.md @@ -11,9 +11,9 @@ Here’s a simple comment: // hello, world ``` -In Rust, comments must start with two slashes and continue until the end of the -line. For comments that extend beyond a single line, you’ll need to include -`//` on each line, like this: +In Rust, the idiomatic comment style starts a comment with two slashes, and the +comment continues until the end of the line. For comments that extend beyond a +single line, you’ll need to include `//` on each line, like this: ```rust // So we’re doing something complicated here, long enough that we need @@ -26,9 +26,7 @@ Comments can also be placed at the end of lines containing code: Filename: src/main.rs ```rust -fn main() { - let lucky_number = 7; // I’m feeling lucky today -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs}} ``` But you’ll more often see them used in this format, with the comment on a @@ -37,10 +35,7 @@ separate line above the code it’s annotating: Filename: src/main.rs ```rust -fn main() { - // I’m feeling lucky today - let lucky_number = 7; -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs}} ``` Rust also has another kind of comment, documentation comments, which we’ll diff --git a/src/doc/book/src/ch03-05-control-flow.md b/src/doc/book/src/ch03-05-control-flow.md index ac529d926d..8c6ce75140 100644 --- a/src/doc/book/src/ch03-05-control-flow.md +++ b/src/doc/book/src/ch03-05-control-flow.md @@ -18,15 +18,7 @@ the `if` expression. In the *src/main.rs* file, input the following: Filename: src/main.rs ```rust -fn main() { - let number = 3; - - if number < 5 { - println!("condition was true"); - } else { - println!("condition was false"); - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-26-if-true/src/main.rs}} ``` All `if` expressions start with the keyword `if`, which is followed by a @@ -48,28 +40,20 @@ to the next bit of code. Try running this code; you should see the following output: ```text -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/branches` -condition was true +{{#include ../listings/ch03-common-programming-concepts/no-listing-26-if-true/output.txt}} ``` Let’s try changing the value of `number` to a value that makes the condition `false` to see what happens: ```rust,ignore -let number = 7; +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-27-if-false/src/main.rs:here}} ``` Run the program again, and look at the output: ```text -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/branches` -condition was false +{{#include ../listings/ch03-common-programming-concepts/no-listing-27-if-false/output.txt}} ``` It’s also worth noting that the condition in this code *must* be a `bool`. If @@ -79,27 +63,14 @@ following code: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let number = 3; - - if number { - println!("number was three"); - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/src/main.rs}} ``` The `if` condition evaluates to a value of `3` this time, and Rust throws an error: ```text -error[E0308]: mismatched types - --> src/main.rs:4:8 - | -4 | if number { - | ^^^^^^ expected bool, found integer - | - = note: expected type `bool` - found type `{integer}` +{{#include ../listings/ch03-common-programming-concepts/no-listing-28-if-condition-must-be-bool/output.txt}} ``` The error indicates that Rust expected a `bool` but got an integer. Unlike @@ -112,13 +83,7 @@ expression to the following: Filename: src/main.rs ```rust -fn main() { - let number = 3; - - if number != 0 { - println!("number was something other than zero"); - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-29-if-not-equal-0/src/main.rs}} ``` Running this code will print `number was something other than zero`. @@ -131,30 +96,14 @@ expression. For example: Filename: src/main.rs ```rust -fn main() { - let number = 6; - - if number % 4 == 0 { - println!("number is divisible by 4"); - } else if number % 3 == 0 { - println!("number is divisible by 3"); - } else if number % 2 == 0 { - println!("number is divisible by 2"); - } else { - println!("number is not divisible by 4, 3, or 2"); - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-30-else-if/src/main.rs}} ``` This program has four possible paths it can take. After running it, you should see the following output: ```text -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running `target/debug/branches` -number is divisible by 3 +{{#include ../listings/ch03-common-programming-concepts/no-listing-30-else-if/output.txt}} ``` When this program executes, it checks each `if` expression in turn and executes @@ -176,16 +125,7 @@ statement, as in Listing 3-2. Filename: src/main.rs ```rust -fn main() { - let condition = true; - let number = if condition { - 5 - } else { - 6 - }; - - println!("The value of number is: {}", number); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-02/src/main.rs}} ``` Listing 3-2: Assigning the result of an `if` expression @@ -195,11 +135,7 @@ The `number` variable will be bound to a value based on the outcome of the `if` expression. Run this code to see what happens: ```text -$ cargo run - Compiling branches v0.1.0 (file:///projects/branches) - Finished dev [unoptimized + debuginfo] target(s) in 0.30 secs - Running `target/debug/branches` -The value of number is: 5 +{{#include ../listings/ch03-common-programming-concepts/listing-03-02/output.txt}} ``` Remember that blocks of code evaluate to the last expression in them, and @@ -213,17 +149,7 @@ example, we’ll get an error: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let condition = true; - - let number = if condition { - 5 - } else { - "six" - }; - - println!("The value of number is: {}", number); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/src/main.rs}} ``` When we try to compile this code, we’ll get an error. The `if` and `else` arms @@ -231,19 +157,7 @@ have value types that are incompatible, and Rust indicates exactly where to find the problem in the program: ```text -error[E0308]: if and else have incompatible types - --> src/main.rs:4:18 - | -4 | let number = if condition { - | __________________^ -5 | | 5 -6 | | } else { -7 | | "six" -8 | | }; - | |_____^ expected integer, found &str - | - = note: expected type `{integer}` - found type `&str` +{{#include ../listings/ch03-common-programming-concepts/no-listing-31-arms-must-return-same-type/output.txt}} ``` The expression in the `if` block evaluates to an integer, and the expression in @@ -275,11 +189,7 @@ like this: Filename: src/main.rs ```rust,ignore -fn main() { - loop { - println!("again!"); - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-32-loop/src/main.rs}} ``` When we run this program, we’ll see `again!` printed over and over continuously @@ -287,10 +197,16 @@ until we stop the program manually. Most terminals support a keyboard shortcut, ctrl-c, to interrupt a program that is stuck in a continual loop. Give it a try: + + ```text $ cargo run Compiling loops v0.1.0 (file:///projects/loops) - Finished dev [unoptimized + debuginfo] target(s) in 0.29 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.29s Running `target/debug/loops` again! again! @@ -321,19 +237,7 @@ the loop; that value will be returned out of the loop so you can use it, as shown here: ```rust -fn main() { - let mut counter = 0; - - let result = loop { - counter += 1; - - if counter == 10 { - break counter * 2; - } - }; - - println!("The result is {}", result); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs}} ``` Before the loop, we declare a variable named `counter` and initialize it to @@ -360,17 +264,7 @@ another message and exits. Filename: src/main.rs ```rust -fn main() { - let mut number = 3; - - while number != 0 { - println!("{}!", number); - - number -= 1; - } - - println!("LIFTOFF!!!"); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-03/src/main.rs}} ``` Listing 3-3: Using a `while` loop to run code while a @@ -388,16 +282,7 @@ such as an array. For example, let’s look at Listing 3-4. Filename: src/main.rs ```rust -fn main() { - let a = [10, 20, 30, 40, 50]; - let mut index = 0; - - while index < 5 { - println!("the value is: {}", a[index]); - - index += 1; - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-04/src/main.rs}} ``` Listing 3-4: Looping through each element of a collection @@ -409,15 +294,7 @@ when `index < 5` is no longer true). Running this code will print every element in the array: ```text -$ cargo run - Compiling loops v0.1.0 (file:///projects/loops) - Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs - Running `target/debug/loops` -the value is: 10 -the value is: 20 -the value is: 30 -the value is: 40 -the value is: 50 +{{#include ../listings/ch03-common-programming-concepts/listing-03-04/output.txt}} ``` All five array values appear in the terminal, as expected. Even though `index` @@ -435,13 +312,7 @@ for each item in a collection. A `for` loop looks like the code in Listing 3-5. Filename: src/main.rs ```rust -fn main() { - let a = [10, 20, 30, 40, 50]; - - for element in a.iter() { - println!("the value is: {}", element); - } -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/listing-03-05/src/main.rs}} ``` Listing 3-5: Looping through each element of a collection @@ -452,10 +323,11 @@ importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items. -For example, in the code in Listing 3-4, if you removed an item from the `a` -array but forgot to update the condition to `while index < 4`, the code would -panic. Using the `for` loop, you wouldn’t need to remember to change any other -code if you changed the number of values in the array. +For example, in the code in Listing 3-4, if you changed the definition of the +`a` array to have four elements but forgot to update the condition to `while +index < 4`, the code would panic. Using the `for` loop, you wouldn’t need to +remember to change any other code if you changed the number of values in the +array. The safety and conciseness of `for` loops make them the most commonly used loop construct in Rust. Even in situations in which you want to run some code a @@ -471,12 +343,7 @@ we’ve not yet talked about, `rev`, to reverse the range: Filename: src/main.rs ```rust -fn main() { - for number in (1..4).rev() { - println!("{}!", number); - } - println!("LIFTOFF!!!"); -} +{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-34-for-range/src/main.rs}} ``` This code is a bit nicer, isn’t it? diff --git a/src/doc/book/src/ch04-01-what-is-ownership.md b/src/doc/book/src/ch04-01-what-is-ownership.md index cf8fd209b4..001830083c 100644 --- a/src/doc/book/src/ch04-01-what-is-ownership.md +++ b/src/doc/book/src/ch04-01-what-is-ownership.md @@ -30,14 +30,14 @@ strings. > be described in relation to the stack and the heap later in this chapter, so > here is a brief explanation in preparation. > -> Both the stack and the heap are parts of memory that are available to your code -> to use at runtime, but they are structured in different ways. The stack stores -> values in the order it gets them and removes the values in the opposite order. -> This is referred to as *last in, first out*. Think of a stack of plates: when -> you add more plates, you put them on top of the pile, and when you need a -> plate, you take one off the top. Adding or removing plates from the middle or -> bottom wouldn’t work as well! Adding data is called *pushing onto the stack*, -> and removing data is called *popping off the stack*. +> Both the stack and the heap are parts of memory that are available to your +> code to use at runtime, but they are structured in different ways. The stack +> stores values in the order it gets them and removes the values in the +> opposite order. This is referred to as *last in, first out*. Think of a stack +> of plates: when you add more plates, you put them on top of the pile, and +> when you need a plate, you take one off the top. Adding or removing plates +> from the middle or bottom wouldn’t work as well! Adding data is called +> *pushing onto the stack*, and removing data is called *popping off the stack*. > > All data stored on the stack must have a known, fixed size. Data with an > unknown size at compile time or a size that might change must be stored on @@ -117,11 +117,7 @@ which it’s declared until the end of the current *scope*. Listing 4-1 has comments annotating where the variable `s` is valid. ```rust -{ // s is not valid here, it’s not yet declared - let s = "hello"; // s is valid from this point forward - - // do stuff with s -} // this scope is now over, and s is no longer valid +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-01/src/main.rs:here}} ``` Listing 4-1: A variable and the scope in which it is @@ -147,7 +143,7 @@ data. We’ll use `String` as the example here and concentrate on the parts of `String` that relate to ownership. These aspects also apply to other complex data types, -whether they are provided by the standard library or created by you. We’ll +whether they are provided by the standard library or created by you. We’ll discuss `String` in more depth in Chapter 8. We’ve already seen string literals, where a string value is hardcoded into our @@ -174,11 +170,7 @@ Module Tree”][paths-module-tree] in Chapter 7. This kind of string *can* be mutated: ```rust -let mut s = String::from("hello"); - -s.push_str(", world!"); // push_str() appends a literal to a String - -println!("{}", s); // This will print `hello, world!` +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs:here}} ``` So, what’s the difference here? Why can `String` be mutated but literals @@ -219,12 +211,7 @@ variable that owns it goes out of scope. Here’s a version of our scope example from Listing 4-1 using a `String` instead of a string literal: ```rust -{ - let s = String::from("hello"); // s is valid from this point forward - - // do stuff with s -} // this scope is now over, and s is no - // longer valid +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs:here}} ``` There is a natural point at which we can return the memory our `String` needs @@ -249,8 +236,7 @@ Multiple variables can interact with the same data in different ways in Rust. Let’s look at an example using an integer in Listing 4-2. ```rust -let x = 5; -let y = x; +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-02/src/main.rs:here}} ``` Listing 4-2: Assigning the integer value of variable `x` @@ -265,8 +251,7 @@ onto the stack. Now let’s look at the `String` version: ```rust -let s1 = String::from("hello"); -let s2 = s1; +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs:here}} ``` This looks very similar to the previous code, so we might assume that the way @@ -325,27 +310,14 @@ anything when `s1` goes out of scope. Check out what happens when you try to use `s1` after `s2` is created; it won’t work: ```rust,ignore,does_not_compile -let s1 = String::from("hello"); -let s2 = s1; - -println!("{}, world!", s1); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs:here}} ``` You’ll get an error like this because Rust prevents you from using the invalidated reference: ```text -error[E0382]: use of moved value: `s1` - --> src/main.rs:5:28 - | -3 | let s2 = s1; - | -- value moved here -4 | -5 | println!("{}, world!", s1); - | ^^ value used here after move - | - = note: move occurs because `s1` has type `std::string::String`, which does - not implement the `Copy` trait +{{#include ../listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt}} ``` If you’ve heard the terms *shallow copy* and *deep copy* while working with @@ -377,10 +349,7 @@ programming languages, you’ve probably seen them before. Here’s an example of the `clone` method in action: ```rust -let s1 = String::from("hello"); -let s2 = s1.clone(); - -println!("s1 = {}, s2 = {}", s1, s2); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs:here}} ``` This works just fine and explicitly produces the behavior shown in Figure 4-3, @@ -396,10 +365,7 @@ There’s another wrinkle we haven’t talked about yet. This code using integer part of which was shown in Listing 4-2, works and is valid: ```rust -let x = 5; -let y = x; - -println!("x = {}, y = {}", x, y); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs:here}} ``` But this code seems to contradict what we just learned: we don’t have a call to @@ -444,29 +410,7 @@ showing where variables go into and out of scope. Filename: src/main.rs ```rust -fn main() { - let s = String::from("hello"); // s comes into scope - - takes_ownership(s); // s's value moves into the function... - // ... and so is no longer valid here - - let x = 5; // x comes into scope - - makes_copy(x); // x would move into the function, - // but i32 is Copy, so it’s okay to still - // use x afterward - -} // Here, x goes out of scope, then s. But because s's value was moved, nothing - // special happens. - -fn takes_ownership(some_string: String) { // some_string comes into scope - println!("{}", some_string); -} // Here, some_string goes out of scope and `drop` is called. The backing - // memory is freed. - -fn makes_copy(some_integer: i32) { // some_integer comes into scope - println!("{}", some_integer); -} // Here, some_integer goes out of scope. Nothing special happens. +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-03/src/main.rs}} ``` Listing 4-3: Functions with ownership and scope @@ -485,35 +429,7 @@ similar annotations to those in Listing 4-3. Filename: src/main.rs ```rust -fn main() { - let s1 = gives_ownership(); // gives_ownership moves its return - // value into s1 - - let s2 = String::from("hello"); // s2 comes into scope - - let s3 = takes_and_gives_back(s2); // s2 is moved into - // takes_and_gives_back, which also - // moves its return value into s3 -} // Here, s3 goes out of scope and is dropped. s2 goes out of scope but was - // moved, so nothing happens. s1 goes out of scope and is dropped. - -fn gives_ownership() -> String { // gives_ownership will move its - // return value into the function - // that calls it - - let some_string = String::from("hello"); // some_string comes into scope - - some_string // some_string is returned and - // moves out to the calling - // function -} - -// takes_and_gives_back will take a String and return one -fn takes_and_gives_back(a_string: String) -> String { // a_string comes into - // scope - - a_string // a_string is returned and moves out to the calling function -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-04/src/main.rs}} ``` Listing 4-4: Transferring ownership of return @@ -535,19 +451,7 @@ It’s possible to return multiple values using a tuple, as shown in Listing 4-5 Filename: src/main.rs ```rust -fn main() { - let s1 = String::from("hello"); - - let (s2, len) = calculate_length(s1); - - println!("The length of '{}' is {}.", s2, len); -} - -fn calculate_length(s: String) -> (String, usize) { - let length = s.len(); // len() returns the length of a String - - (s, length) -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-05/src/main.rs}} ``` Listing 4-5: Returning ownership of parameters diff --git a/src/doc/book/src/ch04-02-references-and-borrowing.md b/src/doc/book/src/ch04-02-references-and-borrowing.md index 985f17f172..5554fc3d37 100644 --- a/src/doc/book/src/ch04-02-references-and-borrowing.md +++ b/src/doc/book/src/ch04-02-references-and-borrowing.md @@ -12,17 +12,7 @@ value: Filename: src/main.rs ```rust -fn main() { - let s1 = String::from("hello"); - - let len = calculate_length(&s1); - - println!("The length of '{}' is {}.", s1, len); -} - -fn calculate_length(s: &String) -> usize { - s.len() -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs:all}} ``` First, notice that all the tuple code in the variable declaration and the @@ -46,12 +36,7 @@ s1` Let’s take a closer look at the function call here: ```rust -# fn calculate_length(s: &String) -> usize { -# s.len() -# } -let s1 = String::from("hello"); - -let len = calculate_length(&s1); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs:here}} ``` The `&s1` syntax lets us create a reference that *refers* to the value of `s1` @@ -62,10 +47,7 @@ Likewise, the signature of the function uses `&` to indicate that the type of the parameter `s` is a reference. Let’s add some explanatory annotations: ```rust -fn calculate_length(s: &String) -> usize { // s is a reference to a String - s.len() -} // Here, s goes out of scope. But because it does not have ownership of what - // it refers to, nothing happens. +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs:here}} ``` The scope in which the variable `s` is valid is the same as any function @@ -84,15 +66,7 @@ Listing 4-6. Spoiler alert: it doesn’t work! Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let s = String::from("hello"); - - change(&s); -} - -fn change(some_string: &String) { - some_string.push_str(", world"); -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-06/src/main.rs}} ``` Listing 4-6: Attempting to modify a borrowed value @@ -100,13 +74,7 @@ fn change(some_string: &String) { Here’s the error: ```text -error[E0596]: cannot borrow immutable borrowed content `*some_string` as mutable - --> error.rs:8:5 - | -7 | fn change(some_string: &String) { - | ------- use `&mut String` here to make mutable -8 | some_string.push_str(", world"); - | ^^^^^^^^^^^ cannot borrow as mutable +{{#include ../listings/ch04-understanding-ownership/listing-04-06/output.txt}} ``` Just as variables are immutable by default, so are references. We’re not @@ -119,15 +87,7 @@ We can fix the error in the code from Listing 4-6 with just a small tweak: Filename: src/main.rs ```rust -fn main() { - let mut s = String::from("hello"); - - change(&mut s); -} - -fn change(some_string: &mut String) { - some_string.push_str(", world"); -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs}} ``` First, we had to change `s` to be `mut`. Then we had to create a mutable @@ -141,27 +101,13 @@ fail: Filename: src/main.rs ```rust,ignore,does_not_compile -let mut s = String::from("hello"); - -let r1 = &mut s; -let r2 = &mut s; - -println!("{}, {}", r1, r2); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs:here}} ``` Here’s the error: ```text -error[E0499]: cannot borrow `s` as mutable more than once at a time - --> src/main.rs:5:14 - | -4 | let r1 = &mut s; - | ------ first mutable borrow occurs here -5 | let r2 = &mut s; - | ^^^^^^ second mutable borrow occurs here -6 | -7 | println!("{}, {}", r1, r2); - | -- first borrow later used here +{{#include ../listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt}} ``` This restriction allows for mutation but in a very controlled fashion. It’s @@ -184,43 +130,20 @@ As always, we can use curly brackets to create a new scope, allowing for multiple mutable references, just not *simultaneous* ones: ```rust -let mut s = String::from("hello"); - -{ - let r1 = &mut s; - -} // r1 goes out of scope here, so we can make a new reference with no problems. - -let r2 = &mut s; +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs:here}} ``` A similar rule exists for combining mutable and immutable references. This code results in an error: ```rust,ignore,does_not_compile -let mut s = String::from("hello"); - -let r1 = &s; // no problem -let r2 = &s; // no problem -let r3 = &mut s; // BIG PROBLEM - -println!("{}, {}, and {}", r1, r2, r3); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs:here}} ``` Here’s the error: ```text -error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable - --> src/main.rs:6:14 - | -4 | let r1 = &s; // no problem - | -- immutable borrow occurs here -5 | let r2 = &s; // no problem -6 | let r3 = &mut s; // BIG PROBLEM - | ^^^^^^ mutable borrow occurs here -7 | -8 | println!("{}, {}, and {}", r1, r2, r3); - | -- immutable borrow later used here +{{#include ../listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt}} ``` Whew! We *also* cannot have a mutable reference while we have an immutable one. @@ -235,15 +158,7 @@ compile because the last usage of the immutable references occurs before the mutable reference is introduced: ```rust,edition2018 -let mut s = String::from("hello"); - -let r1 = &s; // no problem -let r2 = &s; // no problem -println!("{} and {}", r1, r2); -// r1 and r2 are no longer used after this point - -let r3 = &mut s; // no problem -println!("{}", r3); +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs:here}} ``` The scopes of the immutable references `r1` and `r2` end after the `println!` @@ -271,29 +186,13 @@ compile-time error: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let reference_to_nothing = dangle(); -} - -fn dangle() -> &String { - let s = String::from("hello"); - - &s -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs}} ``` Here’s the error: ```text -error[E0106]: missing lifetime specifier - --> main.rs:5:16 - | -5 | fn dangle() -> &String { - | ^ expected lifetime parameter - | - = help: this function's return type contains a borrowed value, but there is - no value for it to be borrowed from - = help: consider giving it a 'static lifetime +{{#include ../listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt}} ``` This error message refers to a feature we haven’t covered yet: lifetimes. We’ll @@ -311,13 +210,7 @@ Let’s take a closer look at exactly what’s happening at each stage of our Filename: src/main.rs ```rust,ignore,does_not_compile -fn dangle() -> &String { // dangle returns a reference to a String - - let s = String::from("hello"); // s is a new String - - &s // we return a reference to the String, s -} // Here, s goes out of scope, and is dropped. Its memory goes away. - // Danger! +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs:here}} ``` Because `s` is created inside `dangle`, when the code of `dangle` is finished, @@ -328,11 +221,7 @@ won’t let us do this. The solution here is to return the `String` directly: ```rust -fn no_dangle() -> String { - let s = String::from("hello"); - - s -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs:here}} ``` This works without any problems. Ownership is moved out, and nothing is diff --git a/src/doc/book/src/ch04-03-slices.md b/src/doc/book/src/ch04-03-slices.md index 969884cf47..902cf3a9a8 100644 --- a/src/doc/book/src/ch04-03-slices.md +++ b/src/doc/book/src/ch04-03-slices.md @@ -23,17 +23,7 @@ end of the word. Let’s try that, as shown in Listing 4-7. Filename: src/main.rs ```rust -fn first_word(s: &String) -> usize { - let bytes = s.as_bytes(); - - for (i, &item) in bytes.iter().enumerate() { - if item == b' ' { - return i; - } - } - - s.len() -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:here}} ``` Listing 4-7: The `first_word` function that returns a @@ -44,13 +34,13 @@ a value is a space, we’ll convert our `String` to an array of bytes using the `as_bytes` method: ```rust,ignore -let bytes = s.as_bytes(); +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:as_bytes}} ``` Next, we create an iterator over the array of bytes using the `iter` method: ```rust,ignore -for (i, &item) in bytes.iter().enumerate() { +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:iter}} ``` We’ll discuss iterators in more detail in Chapter 13. For now, know that `iter` @@ -71,12 +61,7 @@ using the byte literal syntax. If we find a space, we return the position. Otherwise, we return the length of the string by using `s.len()`: ```rust,ignore - if item == b' ' { - return i; - } -} - -s.len() +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-07/src/main.rs:inside_for}} ``` We now have a way to find out the index of the end of the first word in the @@ -89,28 +74,7 @@ uses the `first_word` function from Listing 4-7. Filename: src/main.rs ```rust -# fn first_word(s: &String) -> usize { -# let bytes = s.as_bytes(); -# -# for (i, &item) in bytes.iter().enumerate() { -# if item == b' ' { -# return i; -# } -# } -# -# s.len() -# } -# -fn main() { - let mut s = String::from("hello world"); - - let word = first_word(&s); // word will get the value 5 - - s.clear(); // this empties the String, making it equal to "" - - // word still has the value 5 here, but there's no more string that - // we could meaningfully use the value 5 with. word is now totally invalid! -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-08/src/main.rs:here}} ``` Listing 4-8: Storing the result from calling the @@ -142,10 +106,7 @@ Luckily, Rust has a solution to this problem: string slices. A *string slice* is a reference to part of a `String`, and it looks like this: ```rust -let s = String::from("hello world"); - -let hello = &s[0..5]; -let world = &s[6..11]; +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-17-slice/src/main.rs:here}} ``` This is similar to taking a reference to the whole `String` but with the extra @@ -214,17 +175,7 @@ slice. The type that signifies “string slice” is written as `&str`: Filename: src/main.rs ```rust -fn first_word(s: &String) -> &str { - let bytes = s.as_bytes(); - - for (i, &item) in bytes.iter().enumerate() { - if item == b' ' { - return &s[0..i]; - } - } - - &s[..] -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-18-first-word-slice/src/main.rs:here}} ``` We get the index for the end of the word in the same way as we did in Listing @@ -255,31 +206,13 @@ compile-time error: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let mut s = String::from("hello world"); - - let word = first_word(&s); - - s.clear(); // error! - - println!("the first word is: {}", word); -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-19-slice-error/src/main.rs:here}} ``` Here’s the compiler error: ```text -error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable - --> src/main.rs:18:5 - | -16 | let word = first_word(&s); - | -- immutable borrow occurs here -17 | -18 | s.clear(); // error! - | ^^^^^^^^^ mutable borrow occurs here -19 | -20 | println!("the first word is: {}", word); - | ---- immutable borrow later used here +{{#include ../listings/ch04-understanding-ownership/no-listing-19-slice-error/output.txt}} ``` Recall from the borrowing rules that if we have an immutable reference to @@ -315,7 +248,7 @@ instead because it allows us to use the same function on both `&String` values and `&str` values. ```rust,ignore -fn first_word(s: &str) -> &str { +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-09/src/main.rs:here}} ``` Listing 4-9: Improving the `first_word` function by using @@ -329,32 +262,7 @@ without losing any functionality: Filename: src/main.rs ```rust -# fn first_word(s: &str) -> &str { -# let bytes = s.as_bytes(); -# -# for (i, &item) in bytes.iter().enumerate() { -# if item == b' ' { -# return &s[0..i]; -# } -# } -# -# &s[..] -# } -fn main() { - let my_string = String::from("hello world"); - - // first_word works on slices of `String`s - let word = first_word(&my_string[..]); - - let my_string_literal = "hello world"; - - // first_word works on slices of string literals - let word = first_word(&my_string_literal[..]); - - // Because string literals *are* string slices already, - // this works too, without the slice syntax! - let word = first_word(my_string_literal); -} +{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-09/src/main.rs:usage}} ``` ### Other Slices diff --git a/src/doc/book/src/ch05-01-defining-structs.md b/src/doc/book/src/ch05-01-defining-structs.md index 17fa72a02f..04479e5ced 100644 --- a/src/doc/book/src/ch05-01-defining-structs.md +++ b/src/doc/book/src/ch05-01-defining-structs.md @@ -13,12 +13,7 @@ the pieces of data, which we call *fields*. For example, Listing 5-1 shows a struct that stores information about a user account. ```rust -struct User { - username: String, - email: String, - sign_in_count: u64, - active: bool, -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-01/src/main.rs:here}} ``` Listing 5-1: A `User` struct definition @@ -34,19 +29,7 @@ in that template with particular data to create values of the type. For example, we can declare a particular user as shown in Listing 5-2. ```rust -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -let user1 = User { - email: String::from("someone@example.com"), - username: String::from("someusername123"), - active: true, - sign_in_count: 1, -}; +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-02/src/main.rs:here}} ``` Listing 5-2: Creating an instance of the `User` @@ -59,21 +42,7 @@ the dot notation and assigning into a particular field. Listing 5-3 shows how to change the value in the `email` field of a mutable `User` instance. ```rust -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -let mut user1 = User { - email: String::from("someone@example.com"), - username: String::from("someusername123"), - active: true, - sign_in_count: 1, -}; - -user1.email = String::from("anotheremail@example.com"); +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-03/src/main.rs:here}} ``` Listing 5-3: Changing the value in the `email` field of a @@ -89,21 +58,7 @@ the given email and username. The `active` field gets the value of `true`, and the `sign_in_count` gets a value of `1`. ```rust -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -fn build_user(email: String, username: String) -> User { - User { - email: email, - username: username, - active: true, - sign_in_count: 1, - } -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-04/src/main.rs:here}} ``` Listing 5-4: A `build_user` function that takes an email @@ -122,21 +77,7 @@ Listing 5-4, we can use the *field init shorthand* syntax to rewrite repetition of `email` and `username`, as shown in Listing 5-5. ```rust -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -fn build_user(email: String, username: String) -> User { - User { - email, - username, - active: true, - sign_in_count: 1, - } -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-05/src/main.rs:here}} ``` Listing 5-5: A `build_user` function that uses field init @@ -159,26 +100,7 @@ the update syntax. We set new values for `email` and `username` but otherwise use the same values from `user1` that we created in Listing 5-2. ```rust -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -# let user1 = User { -# email: String::from("someone@example.com"), -# username: String::from("someusername123"), -# active: true, -# sign_in_count: 1, -# }; -# -let user2 = User { - email: String::from("another@example.com"), - username: String::from("anotherusername567"), - active: user1.active, - sign_in_count: user1.sign_in_count, -}; +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-06/src/main.rs:here}} ``` Listing 5-6: Creating a new `User` instance using some of @@ -189,25 +111,7 @@ shown in Listing 5-7. The syntax `..` specifies that the remaining fields not explicitly set should have the same value as the fields in the given instance. ```rust -# struct User { -# username: String, -# email: String, -# sign_in_count: u64, -# active: bool, -# } -# -# let user1 = User { -# email: String::from("someone@example.com"), -# username: String::from("someusername123"), -# active: true, -# sign_in_count: 1, -# }; -# -let user2 = User { - email: String::from("another@example.com"), - username: String::from("anotherusername567"), - ..user1 -}; +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-07/src/main.rs:here}} ``` Listing 5-7: Using struct update syntax to set new @@ -232,11 +136,7 @@ followed by the types in the tuple. For example, here are definitions and usages of two tuple structs named `Color` and `Point`: ```rust -struct Color(i32, i32, i32); -struct Point(i32, i32, i32); - -let black = Color(0, 0, 0); -let origin = Point(0, 0, 0); +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-01-tuple-structs/src/main.rs:here}} ``` Note that the `black` and `origin` values are different types, because they’re @@ -271,6 +171,8 @@ itself. We’ll discuss traits in Chapter 10. > > Filename: src/main.rs > +> +> > ```rust,ignore,does_not_compile > struct User { > username: &str, @@ -292,19 +194,35 @@ itself. We’ll discuss traits in Chapter 10. > The compiler will complain that it needs lifetime specifiers: > > ```text +> $ cargo run +> Compiling structs v0.1.0 (file:///projects/structs) > error[E0106]: missing lifetime specifier -> --> +> --> src/main.rs:2:15 > | > 2 | username: &str, > | ^ expected lifetime parameter > > error[E0106]: missing lifetime specifier -> --> +> --> src/main.rs:3:12 > | > 3 | email: &str, > | ^ expected lifetime parameter +> +> error: aborting due to 2 previous errors +> +> For more information about this error, try `rustc --explain E0106`. +> error: could not compile `structs`. +> +> To learn more, run the command again with --verbose. > ``` > > In Chapter 10, we’ll discuss how to fix these errors so you can store > references in structs, but for now, we’ll fix errors like these using owned > types like `String` instead of references like `&str`. + + diff --git a/src/doc/book/src/ch05-02-example-structs.md b/src/doc/book/src/ch05-02-example-structs.md index 46f88f1b8a..03f69d984e 100644 --- a/src/doc/book/src/ch05-02-example-structs.md +++ b/src/doc/book/src/ch05-02-example-structs.md @@ -12,19 +12,7 @@ exactly that in our project’s *src/main.rs*. Filename: src/main.rs ```rust -fn main() { - let width1 = 30; - let height1 = 50; - - println!( - "The area of the rectangle is {} square pixels.", - area(width1, height1) - ); -} - -fn area(width: u32, height: u32) -> u32 { - width * height -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs:all}} ``` Listing 5-8: Calculating the area of a rectangle @@ -33,7 +21,7 @@ specified by separate width and height variables Now, run this program using `cargo run`: ```text -The area of the rectangle is 1500 square pixels. +{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-08/output.txt}} ``` Even though Listing 5-8 works and figures out the area of the rectangle by @@ -44,7 +32,7 @@ rectangle. The issue with this code is evident in the signature of `area`: ```rust,ignore -fn area(width: u32, height: u32) -> u32 { +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-08/src/main.rs:here}} ``` The `area` function is supposed to calculate the area of one rectangle, but the @@ -61,18 +49,7 @@ Listing 5-9 shows another version of our program that uses tuples. Filename: src/main.rs ```rust -fn main() { - let rect1 = (30, 50); - - println!( - "The area of the rectangle is {} square pixels.", - area(rect1) - ); -} - -fn area(dimensions: (u32, u32)) -> u32 { - dimensions.0 * dimensions.1 -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-09/src/main.rs}} ``` Listing 5-9: Specifying the width and height of the @@ -100,23 +77,7 @@ parts, as shown in Listing 5-10. Filename: src/main.rs ```rust -struct Rectangle { - width: u32, - height: u32, -} - -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - - println!( - "The area of the rectangle is {} square pixels.", - area(&rect1) - ); -} - -fn area(rectangle: &Rectangle) -> u32 { - rectangle.width * rectangle.height -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-10/src/main.rs}} ``` Listing 5-10: Defining a `Rectangle` struct @@ -150,16 +111,7 @@ work, however. Filename: src/main.rs ```rust,ignore,does_not_compile -struct Rectangle { - width: u32, - height: u32, -} - -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - - println!("rect1 is {}", rect1); -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-11/src/main.rs}} ``` Listing 5-11: Attempting to print a `Rectangle` @@ -168,7 +120,7 @@ instance When we compile this code, we get an error with this core message: ```text -error[E0277]: `Rectangle` doesn't implement `std::fmt::Display` +{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt:3}} ``` The `println!` macro can do many kinds of formatting, and by default, the curly @@ -185,8 +137,7 @@ implementation of `Display`. If we continue reading the errors, we’ll find this helpful note: ```text -= help: the trait `std::fmt::Display` is not implemented for `Rectangle` -= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead +{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-11/output.txt:9:10}} ``` Let’s try it! The `println!` macro call will now look like `println!("rect1 is @@ -198,14 +149,13 @@ see its value while we’re debugging our code. Compile the code with this change. Drat! We still get an error: ```text -error[E0277]: `Rectangle` doesn't implement `std::fmt::Debug` +{{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt:3}} ``` But again, the compiler gives us a helpful note: ```text -= help: the trait `std::fmt::Debug` is not implemented for `Rectangle` -= note: add `#[derive(Debug)]` or manually implement `std::fmt::Debug` +{{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-01-debug/output.txt:9:10}} ``` Rust *does* include functionality to print out debugging information, but we @@ -216,17 +166,7 @@ definition, as shown in Listing 5-12. Filename: src/main.rs ```rust -#[derive(Debug)] -struct Rectangle { - width: u32, - height: u32, -} - -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - - println!("rect1 is {:?}", rect1); -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-12/src/main.rs}} ``` Listing 5-12: Adding the annotation to derive the `Debug` @@ -236,7 +176,7 @@ Now when we run the program, we won’t get any errors, and we’ll see the following output: ```text -rect1 is Rectangle { width: 30, height: 50 } +{{#include ../listings/ch05-using-structs-to-structure-related-data/listing-05-12/output.txt}} ``` Nice! It’s not the prettiest output, but it shows the values of all the fields @@ -246,10 +186,7 @@ those cases, we can use `{:#?}` instead of `{:?}` in the `println!` string. When we use the `{:#?}` style in the example, the output will look like this: ```text -rect1 is Rectangle { - width: 30, - height: 50 -} +{{#include ../listings/ch05-using-structs-to-structure-related-data/output-only-02-pretty-debug/output.txt}} ``` Rust has provided a number of traits for us to use with the `derive` annotation diff --git a/src/doc/book/src/ch05-03-method-syntax.md b/src/doc/book/src/ch05-03-method-syntax.md index d8a338c9b6..f074497ca7 100644 --- a/src/doc/book/src/ch05-03-method-syntax.md +++ b/src/doc/book/src/ch05-03-method-syntax.md @@ -17,26 +17,7 @@ in Listing 5-13. Filename: src/main.rs ```rust -#[derive(Debug)] -struct Rectangle { - width: u32, - height: u32, -} - -impl Rectangle { - fn area(&self) -> u32 { - self.width * self.height - } -} - -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - - println!( - "The area of the rectangle is {} square pixels.", - rect1.area() - ); -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-13/src/main.rs}} ``` Listing 5-13: Defining an `area` method on the @@ -90,6 +71,7 @@ provide. > automatically adds in `&`, `&mut`, or `*` so `object` matches the signature of > the method. In other words, the following are the same: > + > ```rust > # #[derive(Debug,Copy,Clone)] > # struct Point { @@ -130,14 +112,7 @@ method. Filename: src/main.rs ```rust,ignore -fn main() { - let rect1 = Rectangle { width: 30, height: 50 }; - let rect2 = Rectangle { width: 10, height: 40 }; - let rect3 = Rectangle { width: 60, height: 45 }; - - println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); - println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-14/src/main.rs}} ``` Listing 5-14: Using the as-yet-unwritten `can_hold` @@ -169,21 +144,7 @@ Listing 5-13, shown in Listing 5-15. Filename: src/main.rs ```rust -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -# -impl Rectangle { - fn area(&self) -> u32 { - self.width * self.height - } - - fn can_hold(&self, other: &Rectangle) -> bool { - self.width > other.width && self.height > other.height - } -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-15/src/main.rs:here}} ``` Listing 5-15: Implementing the `can_hold` method on @@ -212,17 +173,7 @@ specify the same value twice: Filename: src/main.rs ```rust -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -# -impl Rectangle { - fn square(size: u32) -> Rectangle { - Rectangle { width: size, height: size } - } -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/no-listing-03-associated-functions/src/main.rs:here}} ``` To call this associated function, we use the `::` syntax with the struct name; @@ -237,23 +188,7 @@ Each struct is allowed to have multiple `impl` blocks. For example, Listing in its own `impl` block. ```rust -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -# -impl Rectangle { - fn area(&self) -> u32 { - self.width * self.height - } -} - -impl Rectangle { - fn can_hold(&self, other: &Rectangle) -> bool { - self.width > other.width && self.height > other.height - } -} +{{#rustdoc_include ../listings/ch05-using-structs-to-structure-related-data/listing-05-16/src/main.rs:here}} ``` Listing 5-16: Rewriting Listing 5-15 using multiple `impl` diff --git a/src/doc/book/src/ch06-01-defining-an-enum.md b/src/doc/book/src/ch06-01-defining-an-enum.md index 0d25afbb68..1067af06e2 100644 --- a/src/doc/book/src/ch06-01-defining-an-enum.md +++ b/src/doc/book/src/ch06-01-defining-an-enum.md @@ -19,10 +19,7 @@ listing the possible kinds an IP address can be, `V4` and `V6`. These are the variants of the enum: ```rust -enum IpAddrKind { - V4, - V6, -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:def}} ``` `IpAddrKind` is now a custom data type that we can use elsewhere in our code. @@ -32,13 +29,7 @@ enum IpAddrKind { We can create instances of each of the two variants of `IpAddrKind` like this: ```rust -# enum IpAddrKind { -# V4, -# V6, -# } -# -let four = IpAddrKind::V4; -let six = IpAddrKind::V6; +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:instance}} ``` Note that the variants of the enum are namespaced under its identifier, and we @@ -48,26 +39,13 @@ both values `IpAddrKind::V4` and `IpAddrKind::V6` are of the same type: `IpAddrKind`: ```rust -# enum IpAddrKind { -# V4, -# V6, -# } -# -fn route(ip_kind: IpAddrKind) { } +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:fn}} ``` And we can call this function with either variant: ```rust -# enum IpAddrKind { -# V4, -# V6, -# } -# -# fn route(ip_kind: IpAddrKind) { } -# -route(IpAddrKind::V4); -route(IpAddrKind::V6); +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-01-defining-enums/src/main.rs:fn_call}} ``` Using enums has even more advantages. Thinking more about our IP address type, @@ -76,25 +54,7 @@ only know what *kind* it is. Given that you just learned about structs in Chapter 5, you might tackle this problem as shown in Listing 6-1. ```rust -enum IpAddrKind { - V4, - V6, -} - -struct IpAddr { - kind: IpAddrKind, - address: String, -} - -let home = IpAddr { - kind: IpAddrKind::V4, - address: String::from("127.0.0.1"), -}; - -let loopback = IpAddr { - kind: IpAddrKind::V6, - address: String::from("::1"), -}; +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-01/src/main.rs:here}} ``` Listing 6-1: Storing the data and `IpAddrKind` variant of @@ -115,14 +75,7 @@ variant. This new definition of the `IpAddr` enum says that both `V4` and `V6` variants will have associated `String` values: ```rust -enum IpAddr { - V4(String), - V6(String), -} - -let home = IpAddr::V4(String::from("127.0.0.1")); - -let loopback = IpAddr::V6(String::from("::1")); +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-02-enum-with-data/src/main.rs:here}} ``` We attach data to each variant of the enum directly, so there is no need for an @@ -136,14 +89,7 @@ still express `V6` addresses as one `String` value, we wouldn’t be able to wit a struct. Enums handle this case with ease: ```rust -enum IpAddr { - V4(u8, u8, u8, u8), - V6(String), -} - -let home = IpAddr::V4(127, 0, 0, 1); - -let loopback = IpAddr::V6(String::from("::1")); +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-03-variants-with-different-data/src/main.rs:here}} ``` We’ve shown several different ways to define data structures to store version @@ -186,12 +132,7 @@ Let’s look at another example of an enum in Listing 6-2: this one has a wide variety of types embedded in its variants. ```rust -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(i32, i32, i32), -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs:here}} ``` Listing 6-2: A `Message` enum whose variants each store @@ -211,13 +152,7 @@ type. The following structs could hold the same data that the preceding enum variants hold: ```rust -struct QuitMessage; // unit struct -struct MoveMessage { - x: i32, - y: i32, -} -struct WriteMessage(String); // tuple struct -struct ChangeColorMessage(i32, i32, i32); // tuple struct +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-04-structs-similar-to-message-enum/src/main.rs:here}} ``` But if we used the different structs, which each have their own type, we @@ -229,21 +164,7 @@ define methods on structs using `impl`, we’re also able to define methods on enums. Here’s a method named `call` that we could define on our `Message` enum: ```rust -# enum Message { -# Quit, -# Move { x: i32, y: i32 }, -# Write(String), -# ChangeColor(i32, i32, i32), -# } -# -impl Message { - fn call(&self) { - // method body would be defined here - } -} - -let m = Message::Write(String::from("hello")); -m.call(); +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-05-methods-on-enums/src/main.rs:here}} ``` The body of the method would use `self` to get the value that we called the @@ -319,10 +240,7 @@ For now, all you need to know is that `` means the `Some` variant of the using `Option` values to hold number types and string types: ```rust -let some_number = Some(5); -let some_string = Some("a string"); - -let absent_number: Option = None; +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-06-option-examples/src/main.rs:here}} ``` If we use `None` rather than `Some`, we need to tell Rust what type of @@ -340,22 +258,13 @@ definitely a valid value. For example, this code won’t compile because it’s trying to add an `i8` to an `Option`: ```rust,ignore,does_not_compile -let x: i8 = 5; -let y: Option = Some(5); - -let sum = x + y; +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/src/main.rs:here}} ``` If we run this code, we get an error message like this: ```text -error[E0277]: the trait bound `i8: std::ops::Add>` is -not satisfied - --> - | -5 | let sum = x + y; - | ^ no implementation for `i8 + std::option::Option` - | +{{#include ../listings/ch06-enums-and-pattern-matching/no-listing-07-cant-use-option-directly/output.txt}} ``` Intense! In effect, this error message means that Rust doesn’t understand how diff --git a/src/doc/book/src/ch06-02-match.md b/src/doc/book/src/ch06-02-match.md index b00459beb9..f40380867f 100644 --- a/src/doc/book/src/ch06-02-match.md +++ b/src/doc/book/src/ch06-02-match.md @@ -20,21 +20,7 @@ similar way as the counting machine, determine which coin it is and return its value in cents, as shown here in Listing 6-3. ```rust -enum Coin { - Penny, - Nickel, - Dime, - Quarter, -} - -fn value_in_cents(coin: Coin) -> u8 { - match coin { - Coin::Penny => 1, - Coin::Nickel => 5, - Coin::Dime => 10, - Coin::Quarter => 25, - } -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-03/src/main.rs:here}} ``` Listing 6-3: An enum and a `match` expression that has @@ -69,24 +55,7 @@ following code would print “Lucky penny!” every time the method was called w a `Coin::Penny` but would still return the last value of the block, `1`: ```rust -# enum Coin { -# Penny, -# Nickel, -# Dime, -# Quarter, -# } -# -fn value_in_cents(coin: Coin) -> u8 { - match coin { - Coin::Penny => { - println!("Lucky penny!"); - 1 - }, - Coin::Nickel => 5, - Coin::Dime => 10, - Coin::Quarter => 25, - } -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-08-match-arm-multiple-lines/src/main.rs:here}} ``` ### Patterns that Bind to Values @@ -103,19 +72,7 @@ our `enum` by changing the `Quarter` variant to include a `UsState` value stored inside it, which we’ve done here in Listing 6-4. ```rust -#[derive(Debug)] // so we can inspect the state in a minute -enum UsState { - Alabama, - Alaska, - // --snip-- -} - -enum Coin { - Penny, - Nickel, - Dime, - Quarter(UsState), -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-04/src/main.rs:here}} ``` Listing 6-4: A `Coin` enum in which the `Quarter` variant @@ -132,30 +89,7 @@ pattern that matches values of the variant `Coin::Quarter`. When a quarter’s state. Then we can use `state` in the code for that arm, like so: ```rust -# #[derive(Debug)] -# enum UsState { -# Alabama, -# Alaska, -# } -# -# enum Coin { -# Penny, -# Nickel, -# Dime, -# Quarter(UsState), -# } -# -fn value_in_cents(coin: Coin) -> u8 { - match coin { - Coin::Penny => 1, - Coin::Nickel => 5, - Coin::Dime => 10, - Coin::Quarter(state) => { - println!("State quarter from {:?}!", state); - 25 - }, - } -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-09-variable-in-pattern/src/main.rs:here}} ``` If we were to call `value_in_cents(Coin::Quarter(UsState::Alaska))`, `coin` @@ -182,16 +116,7 @@ This function is very easy to write, thanks to `match`, and will look like Listing 6-5. ```rust -fn plus_one(x: Option) -> Option { - match x { - None => None, - Some(i) => Some(i + 1), - } -} - -let five = Some(5); -let six = plus_one(five); -let none = plus_one(None); +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:here}} ``` Listing 6-5: A function that uses a `match` expression on @@ -202,14 +127,14 @@ Let’s examine the first execution of `plus_one` in more detail. When we call value `Some(5)`. We then compare that against each match arm. ```rust,ignore -None => None, +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:first_arm}} ``` The `Some(5)` value doesn’t match the pattern `None`, so we continue to the next arm. ```rust,ignore -Some(i) => Some(i + 1), +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:second_arm}} ``` Does `Some(5)` match `Some(i)`? Why yes it does! We have the same variant. The @@ -221,7 +146,7 @@ Now let’s consider the second call of `plus_one` in Listing 6-5, where `x` is `None`. We enter the `match` and compare to the first arm. ```rust,ignore -None => None, +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-05/src/main.rs:first_arm}} ``` It matches! There’s no value to add to, so the program stops and returns the @@ -240,11 +165,7 @@ There’s one other aspect of `match` we need to discuss. Consider this version of our `plus_one` function that has a bug and won’t compile: ```rust,ignore,does_not_compile -fn plus_one(x: Option) -> Option { - match x { - Some(i) => Some(i + 1), - } -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/src/main.rs:here}} ``` We didn’t handle the `None` case, so this code will cause a bug. Luckily, it’s @@ -252,11 +173,7 @@ a bug Rust knows how to catch. If we try to compile this code, we’ll get this error: ```text -error[E0004]: non-exhaustive patterns: `None` not covered - --> - | -6 | match x { - | ^ pattern `None` not covered +{{#include ../listings/ch06-enums-and-pattern-matching/no-listing-10-non-exhaustive-match/output.txt}} ``` Rust knows that we didn’t cover every possible case and even knows which @@ -275,14 +192,7 @@ care about the values 1, 3, 5, and 7, we don’t want to have to list out 0, 2, special pattern `_` instead: ```rust -let some_u8_value = 0u8; -match some_u8_value { - 1 => println!("one"), - 3 => println!("three"), - 5 => println!("five"), - 7 => println!("seven"), - _ => (), -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-11-underscore-placeholder/src/main.rs:here}} ``` The `_` pattern will match any value. By putting it after our other arms, the diff --git a/src/doc/book/src/ch06-03-if-let.md b/src/doc/book/src/ch06-03-if-let.md index 6583546387..3eb0cc348f 100644 --- a/src/doc/book/src/ch06-03-if-let.md +++ b/src/doc/book/src/ch06-03-if-let.md @@ -6,11 +6,7 @@ program in Listing 6-6 that matches on an `Option` value but only wants to execute code if the value is 3. ```rust -let some_u8_value = Some(0u8); -match some_u8_value { - Some(3) => println!("three"), - _ => (), -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-06/src/main.rs:here}} ``` Listing 6-6: A `match` that only cares about executing @@ -25,10 +21,7 @@ Instead, we could write this in a shorter way using `if let`. The following code behaves the same as the `match` in Listing 6-6: ```rust -# let some_u8_value = Some(0u8); -if let Some(3) = some_u8_value { - println!("three"); -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-12-if-let/src/main.rs:here}} ``` The syntax `if let` takes a pattern and an expression separated by an equal @@ -53,48 +46,13 @@ announcing the state of the quarters, we could do that with a `match` expression like this: ```rust -# #[derive(Debug)] -# enum UsState { -# Alabama, -# Alaska, -# } -# -# enum Coin { -# Penny, -# Nickel, -# Dime, -# Quarter(UsState), -# } -# let coin = Coin::Penny; -let mut count = 0; -match coin { - Coin::Quarter(state) => println!("State quarter from {:?}!", state), - _ => count += 1, -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-13-count-and-announce-match/src/main.rs:here}} ``` Or we could use an `if let` and `else` expression like this: ```rust -# #[derive(Debug)] -# enum UsState { -# Alabama, -# Alaska, -# } -# -# enum Coin { -# Penny, -# Nickel, -# Dime, -# Quarter(UsState), -# } -# let coin = Coin::Penny; -let mut count = 0; -if let Coin::Quarter(state) = coin { - println!("State quarter from {:?}!", state); -} else { - count += 1; -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/no-listing-14-count-and-announce-if-let-else/src/main.rs:here}} ``` If you have a situation in which your program has logic that is too verbose to diff --git a/src/doc/book/src/ch07-01-packages-and-crates.md b/src/doc/book/src/ch07-01-packages-and-crates.md index 1b7a163af9..2bf2f112d2 100644 --- a/src/doc/book/src/ch07-01-packages-and-crates.md +++ b/src/doc/book/src/ch07-01-packages-and-crates.md @@ -4,7 +4,7 @@ The first parts of the module system we’ll cover are packages and crates. A crate is a binary or library. The *crate root* is a source file that the Rust compiler starts from and makes up the root module of your crate (we’ll explain modules in depth in the [“Defining Modules to Control Scope and -Privacy”][modules]) section. A *package* is one or more crates +Privacy”][modules] section). A *package* is one or more crates that provide a set of functionality. A package contains a *Cargo.toml* file that describes how to build those crates. diff --git a/src/doc/book/src/ch07-02-defining-modules-to-control-scope-and-privacy.md b/src/doc/book/src/ch07-02-defining-modules-to-control-scope-and-privacy.md index d2674f3f19..d46ef9b0c0 100644 --- a/src/doc/book/src/ch07-02-defining-modules-to-control-scope-and-privacy.md +++ b/src/doc/book/src/ch07-02-defining-modules-to-control-scope-and-privacy.md @@ -29,22 +29,8 @@ Listing 7-1 into *src/lib.rs* to define some modules and function signatures. Filename: src/lib.rs -```rust,ignore -mod front_of_house { - mod hosting { - fn add_to_waitlist() {} - - fn seat_at_table() {} - } - - mod serving { - fn take_order() {} - - fn serve_order() {} - - fn take_payment() {} - } -} +```rust +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-01/src/lib.rs:here}} ``` Listing 7-1: A `front_of_house` module containing other diff --git a/src/doc/book/src/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md b/src/doc/book/src/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md index ad584b72b4..d765a663b9 100644 --- a/src/doc/book/src/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md +++ b/src/doc/book/src/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.md @@ -28,19 +28,7 @@ in a bit. Filename: src/lib.rs ```rust,ignore,does_not_compile -mod front_of_house { - mod hosting { - fn add_to_waitlist() {} - } -} - -pub fn eat_at_restaurant() { - // Absolute path - crate::front_of_house::hosting::add_to_waitlist(); - - // Relative path - front_of_house::hosting::add_to_waitlist(); -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-03/src/lib.rs}} ``` Listing 7-3: Calling the `add_to_waitlist` function using @@ -80,19 +68,7 @@ Let’s try to compile Listing 7-3 and find out why it won’t compile yet! The error we get is shown in Listing 7-4. ```text -$ cargo build - Compiling restaurant v0.1.0 (file:///projects/restaurant) -error[E0603]: module `hosting` is private - --> src/lib.rs:9:28 - | -9 | crate::front_of_house::hosting::add_to_waitlist(); - | ^^^^^^^ - -error[E0603]: module `hosting` is private - --> src/lib.rs:12:21 - | -12 | front_of_house::hosting::add_to_waitlist(); - | ^^^^^^^ +{{#include ../listings/ch07-managing-growing-projects/listing-07-03/output.txt}} ``` Listing 7-4: Compiler errors from building the code in @@ -134,19 +110,7 @@ access to the `add_to_waitlist` function in the child module, so we mark the Filename: src/lib.rs ```rust,ignore,does_not_compile -mod front_of_house { - pub mod hosting { - fn add_to_waitlist() {} - } -} - -pub fn eat_at_restaurant() { - // Absolute path - crate::front_of_house::hosting::add_to_waitlist(); - - // Relative path - front_of_house::hosting::add_to_waitlist(); -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-05/src/lib.rs}} ``` Listing 7-5: Declaring the `hosting` module as `pub` to @@ -156,19 +120,7 @@ Unfortunately, the code in Listing 7-5 still results in an error, as shown in Listing 7-6. ```text -$ cargo build - Compiling restaurant v0.1.0 (file:///projects/restaurant) -error[E0603]: function `add_to_waitlist` is private - --> src/lib.rs:9:37 - | -9 | crate::front_of_house::hosting::add_to_waitlist(); - | ^^^^^^^^^^^^^^^ - -error[E0603]: function `add_to_waitlist` is private - --> src/lib.rs:12:30 - | -12 | front_of_house::hosting::add_to_waitlist(); - | ^^^^^^^^^^^^^^^ +{{#include ../listings/ch07-managing-growing-projects/listing-07-05/output.txt}} ``` Listing 7-6: Compiler errors from building the code in @@ -190,20 +142,7 @@ keyword before its definition, as in Listing 7-7. Filename: src/lib.rs ```rust -mod front_of_house { - pub mod hosting { - pub fn add_to_waitlist() {} - } -} - -pub fn eat_at_restaurant() { - // Absolute path - crate::front_of_house::hosting::add_to_waitlist(); - - // Relative path - front_of_house::hosting::add_to_waitlist(); -} -# fn main() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-07/src/lib.rs:here}} ``` Listing 7-7: Adding the `pub` keyword to `mod hosting` @@ -246,17 +185,7 @@ the path to `serve_order` starting with `super`: Filename: src/lib.rs ```rust -fn serve_order() {} - -mod back_of_house { - fn fix_incorrect_order() { - cook_order(); - super::serve_order(); - } - - fn cook_order() {} -} -# fn main() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-08/src/lib.rs:here}} ``` Listing 7-8: Calling a function using a relative path @@ -287,33 +216,7 @@ or even see which fruit they’ll get. Filename: src/lib.rs ```rust -mod back_of_house { - pub struct Breakfast { - pub toast: String, - seasonal_fruit: String, - } - - impl Breakfast { - pub fn summer(toast: &str) -> Breakfast { - Breakfast { - toast: String::from(toast), - seasonal_fruit: String::from("peaches"), - } - } - } -} - -pub fn eat_at_restaurant() { - // Order a breakfast in the summer with Rye toast - let mut meal = back_of_house::Breakfast::summer("Rye"); - // Change our mind about what bread we'd like - meal.toast = String::from("Wheat"); - println!("I'd like {} toast please", meal.toast); - - // The next line won't compile if we uncomment it; we're not allowed - // to see or modify the seasonal fruit that comes with the meal - // meal.seasonal_fruit = String::from("blueberries"); -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-09/src/lib.rs}} ``` Listing 7-9: A struct with some public fields and some @@ -338,17 +241,7 @@ only need the `pub` before the `enum` keyword, as shown in Listing 7-10. Filename: src/lib.rs ```rust -mod back_of_house { - pub enum Appetizer { - Soup, - Salad, - } -} - -pub fn eat_at_restaurant() { - let order1 = back_of_house::Appetizer::Soup; - let order2 = back_of_house::Appetizer::Salad; -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-10/src/lib.rs}} ``` Listing 7-10: Designating an enum as public makes all its diff --git a/src/doc/book/src/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md b/src/doc/book/src/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md index 05af46cbdc..3bb5870b59 100644 --- a/src/doc/book/src/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md +++ b/src/doc/book/src/ch07-04-bringing-paths-into-scope-with-the-use-keyword.md @@ -16,20 +16,7 @@ scope of the `eat_at_restaurant` function so we only have to specify Filename: src/lib.rs ```rust -mod front_of_house { - pub mod hosting { - pub fn add_to_waitlist() {} - } -} - -use crate::front_of_house::hosting; - -pub fn eat_at_restaurant() { - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); -} -# fn main() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-11/src/lib.rs:here}} ``` Listing 7-11: Bringing a module into scope with @@ -48,20 +35,7 @@ Listing 7-11. Filename: src/lib.rs ```rust -mod front_of_house { - pub mod hosting { - pub fn add_to_waitlist() {} - } -} - -use front_of_house::hosting; - -pub fn eat_at_restaurant() { - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); -} -# fn main() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-12/src/lib.rs:here}} ``` Listing 7-12: Bringing a module into scope with `use` and @@ -77,20 +51,7 @@ the `add_to_waitlist` function to achieve the same result, as in Listing 7-13. Filename: src/lib.rs ```rust -mod front_of_house { - pub mod hosting { - pub fn add_to_waitlist() {} - } -} - -use crate::front_of_house::hosting::add_to_waitlist; - -pub fn eat_at_restaurant() { - add_to_waitlist(); - add_to_waitlist(); - add_to_waitlist(); -} -# fn main() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-13/src/lib.rs:here}} ``` Listing 7-13: Bringing the `add_to_waitlist` function @@ -111,12 +72,7 @@ crate. Filename: src/main.rs ```rust -use std::collections::HashMap; - -fn main() { - let mut map = HashMap::new(); - map.insert(1, 2); -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-14/src/main.rs}} ``` Listing 7-14: Bringing `HashMap` into scope in an @@ -133,18 +89,7 @@ different parent modules and how to refer to them. Filename: src/lib.rs ```rust -use std::fmt; -use std::io; - -fn function1() -> fmt::Result { - // --snip-- -# Ok(()) -} - -fn function2() -> io::Result<()> { - // --snip-- -# Ok(()) -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-15/src/lib.rs:here}} ``` Listing 7-15: Bringing two types with the same name into @@ -165,18 +110,7 @@ code in Listing 7-15 by renaming one of the two `Result` types using `as`. Filename: src/lib.rs ```rust -use std::fmt::Result; -use std::io::Result as IoResult; - -fn function1() -> Result { - // --snip-- -# Ok(()) -} - -fn function2() -> IoResult<()> { - // --snip-- -# Ok(()) -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-16/src/lib.rs:here}} ``` Listing 7-16: Renaming a type when it’s brought into @@ -202,20 +136,7 @@ changed to `pub use`. Filename: src/lib.rs ```rust -mod front_of_house { - pub mod hosting { - pub fn add_to_waitlist() {} - } -} - -pub use crate::front_of_house::hosting; - -pub fn eat_at_restaurant() { - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); -} -# fn main() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-17/src/lib.rs:here}} ``` Listing 7-17: Making a name available for any code to use @@ -250,8 +171,7 @@ added this line to *Cargo.toml*: Filename: Cargo.toml ```toml -[dependencies] -rand = "0.5.5" +{{#include ../listings/ch02-guessing-game-tutorial/listing-02-02/Cargo.toml:9:}} ``` Adding `rand` as a dependency in *Cargo.toml* tells Cargo to download the @@ -265,10 +185,7 @@ Number”][rand] section in Chapter 2, we brought the `Rng` trait into scope and called the `rand::thread_rng` function: ```rust,ignore -use rand::Rng; -fn main() { - let secret_number = rand::thread_rng().gen_range(1, 101); -} +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-03/src/main.rs:ch07-04}} ``` Members of the Rust community have made many packages available at @@ -298,10 +215,8 @@ Listing 2-4 bring items from `std` into scope: Filename: src/main.rs -```rust -use std::io; -use std::cmp::Ordering; -// ---snip--- +```rust,ignore +{{#rustdoc_include ../listings/ch07-managing-growing-projects/no-listing-01-use-std-unnested/src/main.rs:here}} ``` Instead, we can use nested paths to bring the same items into scope in one @@ -311,9 +226,8 @@ differ, as shown in Listing 7-18. Filename: src/main.rs -```rust -use std::{cmp::Ordering, io}; -// ---snip--- +```rust,ignore +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-18/src/main.rs:here}} ``` Listing 7-18: Specifying a nested path to bring multiple @@ -331,8 +245,7 @@ two `use` statements that share a subpath. For example, Listing 7-19 shows two Filename: src/lib.rs ```rust -use std::io; -use std::io::Write; +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-19/src/lib.rs}} ``` Listing 7-19: Two `use` statements where one is a subpath @@ -345,7 +258,7 @@ the nested path, as shown in Listing 7-20. Filename: src/lib.rs ```rust -use std::io::{self, Write}; +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-20/src/lib.rs}} ``` Listing 7-20: Combining the paths in Listing 7-19 into diff --git a/src/doc/book/src/ch07-05-separating-modules-into-different-files.md b/src/doc/book/src/ch07-05-separating-modules-into-different-files.md index 6b51859afd..cff0e439cf 100644 --- a/src/doc/book/src/ch07-05-separating-modules-into-different-files.md +++ b/src/doc/book/src/ch07-05-separating-modules-into-different-files.md @@ -13,15 +13,7 @@ crates whose crate root file is *src/main.rs*. Filename: src/lib.rs ```rust,ignore -mod front_of_house; - -pub use crate::front_of_house::hosting; - -pub fn eat_at_restaurant() { - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); - hosting::add_to_waitlist(); -} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-21-and-22/src/lib.rs}} ``` Listing 7-21: Declaring the `front_of_house` module whose @@ -32,10 +24,8 @@ And *src/front_of_house.rs* gets the definitions from the body of the Filename: src/front_of_house.rs -```rust -pub mod hosting { - pub fn add_to_waitlist() {} -} +```rust,ignore +{{#rustdoc_include ../listings/ch07-managing-growing-projects/listing-07-21-and-22/src/front_of_house.rs}} ``` Listing 7-22: Definitions inside the `front_of_house` @@ -50,7 +40,7 @@ declaration of the `hosting` module: Filename: src/front_of_house.rs ``` -pub mod hosting; +{{#rustdoc_include ../listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house.rs}} ``` Then we create a *src/front_of_house* directory and a file @@ -60,7 +50,7 @@ Then we create a *src/front_of_house* directory and a file Filename: src/front_of_house/hosting.rs ``` -pub fn add_to_waitlist() {} +{{#rustdoc_include ../listings/ch07-managing-growing-projects/no-listing-02-extracting-hosting/src/front_of_house/hosting.rs}} ``` The module tree remains the same, and the function calls in `eat_at_restaurant` diff --git a/src/doc/book/src/ch08-01-vectors.md b/src/doc/book/src/ch08-01-vectors.md index aaf15381fb..2f93e6b6d2 100644 --- a/src/doc/book/src/ch08-01-vectors.md +++ b/src/doc/book/src/ch08-01-vectors.md @@ -12,7 +12,7 @@ To create a new, empty vector, we can call the `Vec::new` function, as shown in Listing 8-1. ```rust -let v: Vec = Vec::new(); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-01/src/main.rs:here}} ``` Listing 8-1: Creating a new, empty vector to hold values @@ -32,10 +32,12 @@ store once you insert values, so you rarely need to do this type annotation. It’s more common to create a `Vec` that has initial values, and Rust provides the `vec!` macro for convenience. The macro will create a new vector that holds the values you give it. Listing 8-2 creates a new `Vec` that -holds the values `1`, `2`, and `3`. +holds the values `1`, `2`, and `3`. The integer type is `i32` because that’s +the default integer type, as we discussed in the [“Data Types”][data-types] section of Chapter 3. ```rust -let v = vec![1, 2, 3]; +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-02/src/main.rs:here}} ``` Listing 8-2: Creating a new vector containing @@ -51,12 +53,7 @@ To create a vector and then add elements to it, we can use the `push` method, as shown in Listing 8-3. ```rust -let mut v = Vec::new(); - -v.push(5); -v.push(6); -v.push(7); -v.push(8); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-03/src/main.rs:here}} ``` Listing 8-3: Using the `push` method to add values to a @@ -73,12 +70,7 @@ Like any other `struct`, a vector is freed when it goes out of scope, as annotated in Listing 8-4. ```rust -{ - let v = vec![1, 2, 3, 4]; - - // do stuff with v - -} // <- v goes out of scope and is freed here +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-04/src/main.rs:here}} ``` Listing 8-4: Showing where the vector and its elements @@ -100,15 +92,7 @@ Listing 8-5 shows both methods of accessing a value in a vector, either with indexing syntax or the `get` method. ```rust -let v = vec![1, 2, 3, 4, 5]; - -let third: &i32 = &v[2]; -println!("The third element is {}", third); - -match v.get(2) { - Some(third) => println!("The third element is {}", third), - None => println!("There is no third element."), -} +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-05/src/main.rs:here}} ``` Listing 8-5: Using indexing syntax or the `get` method to @@ -127,10 +111,7 @@ that holds five elements and then tries to access an element at index 100, as shown in Listing 8-6. ```rust,should_panic,panics -let v = vec![1, 2, 3, 4, 5]; - -let does_not_exist = &v[100]; -let does_not_exist = v.get(100); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-06/src/main.rs:here}} ``` Listing 8-6: Attempting to access the element at index @@ -160,13 +141,7 @@ the first element in a vector and try to add an element to the end, which won’ work. ```rust,ignore,does_not_compile -let mut v = vec![1, 2, 3, 4, 5]; - -let first = &v[0]; - -v.push(6); - -println!("The first element is: {}", first); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-07/src/main.rs:here}} ``` Listing 8-7: Attempting to add an element to a vector @@ -175,17 +150,7 @@ while holding a reference to an item Compiling this code will result in this error: ```text -error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable - --> src/main.rs:6:5 - | -4 | let first = &v[0]; - | - immutable borrow occurs here -5 | -6 | v.push(6); - | ^^^^^^^^^ mutable borrow occurs here -7 | -8 | println!("The first element is: {}", first); - | ----- immutable borrow later used here +{{#include ../listings/ch08-common-collections/listing-08-07/output.txt}} ``` The code in Listing 8-7 might look like it should work: why should a reference @@ -197,8 +162,8 @@ other where the vector currently is. In that case, the reference to the first element would be pointing to deallocated memory. The borrowing rules prevent programs from ending up in that situation. -> Note: For more on the implementation details of the `Vec` type, see “The -> Rustonomicon” at https://doc.rust-lang.org/stable/nomicon/vec.html. +> Note: For more on the implementation details of the `Vec` type, see [“The +> Rustonomicon”][nomicon]. ### Iterating over the Values in a Vector @@ -208,10 +173,7 @@ all of the elements rather than use indices to access one at a time. Listing in a vector of `i32` values and print them. ```rust -let v = vec![100, 32, 57]; -for i in &v { - println!("{}", i); -} +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-08/src/main.rs:here}} ``` Listing 8-8: Printing each element in a vector by @@ -222,10 +184,7 @@ in order to make changes to all the elements. The `for` loop in Listing 8-9 will add `50` to each element. ```rust -let mut v = vec![100, 32, 57]; -for i in &mut v { - *i += 50; -} +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-09/src/main.rs:here}} ``` Listing 8-9: Iterating over mutable references to @@ -253,17 +212,7 @@ that of the enum. Then we can create a vector that holds that enum and so, ultimately, holds different types. We’ve demonstrated this in Listing 8-10. ```rust -enum SpreadsheetCell { - Int(i32), - Float(f64), - Text(String), -} - -let row = vec![ - SpreadsheetCell::Int(3), - SpreadsheetCell::Text(String::from("blue")), - SpreadsheetCell::Float(10.12), -]; +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-10/src/main.rs:here}} ``` Listing 8-10: Defining an `enum` to store values of @@ -288,4 +237,6 @@ to review the API documentation for all the many useful methods defined on method removes and returns the last element. Let’s move on to the next collection type: `String`! +[data-types]: ch03-02-data-types.html#data-types +[nomicon]: ../nomicon/vec.html [deref]: ch15-02-deref.html#following-the-pointer-to-the-value-with-the-dereference-operator diff --git a/src/doc/book/src/ch08-02-strings.md b/src/doc/book/src/ch08-02-strings.md index f09ebbb98e..bcee93ebd4 100644 --- a/src/doc/book/src/ch08-02-strings.md +++ b/src/doc/book/src/ch08-02-strings.md @@ -48,7 +48,7 @@ as well, starting with the `new` function to create a string, shown in Listing 8-11. ```rust -let mut s = String::new(); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-11/src/main.rs:here}} ``` Listing 8-11: Creating a new, empty `String` @@ -60,12 +60,7 @@ that implements the `Display` trait, as string literals do. Listing 8-12 shows two examples. ```rust -let data = "initial contents"; - -let s = data.to_string(); - -// the method also works on a literal directly: -let s = "initial contents".to_string(); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-12/src/main.rs:here}} ``` Listing 8-12: Using the `to_string` method to create a @@ -78,7 +73,7 @@ literal. The code in Listing 8-13 is equivalent to the code from Listing 8-12 that uses `to_string`. ```rust -let s = String::from("initial contents"); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-13/src/main.rs:here}} ``` Listing 8-13: Using the `String::from` function to create @@ -93,17 +88,7 @@ Remember that strings are UTF-8 encoded, so we can include any properly encoded data in them, as shown in Listing 8-14. ```rust -let hello = String::from("السلام عليكم"); -let hello = String::from("Dobrý den"); -let hello = String::from("Hello"); -let hello = String::from("שָׁלוֹם"); -let hello = String::from("नमस्ते"); -let hello = String::from("こんにちは"); -let hello = String::from("안녕하세요"); -let hello = String::from("你好"); -let hello = String::from("Olá"); -let hello = String::from("Здравствуйте"); -let hello = String::from("Hola"); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-14/src/main.rs:here}} ``` Listing 8-14: Storing greetings in different languages in @@ -123,8 +108,7 @@ We can grow a `String` by using the `push_str` method to append a string slice, as shown in Listing 8-15. ```rust -let mut s = String::from("foo"); -s.push_str("bar"); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-15/src/main.rs:here}} ``` Listing 8-15: Appending a string slice to a `String` @@ -136,10 +120,7 @@ parameter. For example, the code in Listing 8-16 shows that it would be unfortunate if we weren’t able to use `s2` after appending its contents to `s1`. ```rust -let mut s1 = String::from("foo"); -let s2 = "bar"; -s1.push_str(s2); -println!("s2 is {}", s2); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-16/src/main.rs:here}} ``` Listing 8-16: Using a string slice after appending its @@ -153,8 +134,7 @@ The `push` method takes a single character as a parameter and adds it to the the `push` method. ```rust -let mut s = String::from("lo"); -s.push('l'); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-17/src/main.rs:here}} ``` Listing 8-17: Adding one character to a `String` value @@ -168,9 +148,7 @@ Often, you’ll want to combine two existing strings. One way is to use the `+` operator, as shown in Listing 8-18. ```rust -let s1 = String::from("Hello, "); -let s2 = String::from("world!"); -let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-18/src/main.rs:here}} ``` Listing 8-18: Using the `+` operator to combine two @@ -219,11 +197,7 @@ If we need to concatenate multiple strings, the behavior of the `+` operator gets unwieldy: ```rust -let s1 = String::from("tic"); -let s2 = String::from("tac"); -let s3 = String::from("toe"); - -let s = s1 + "-" + &s2 + "-" + &s3; +{{#rustdoc_include ../listings/ch08-common-collections/no-listing-01-concat-multiple-strings/src/main.rs:here}} ``` At this point, `s` will be `tic-tac-toe`. With all of the `+` and `"` @@ -231,11 +205,7 @@ characters, it’s difficult to see what’s going on. For more complicated stri combining, we can use the `format!` macro: ```rust -let s1 = String::from("tic"); -let s2 = String::from("tac"); -let s3 = String::from("toe"); - -let s = format!("{}-{}-{}", s1, s2, s3); +{{#rustdoc_include ../listings/ch08-common-collections/no-listing-02-format/src/main.rs:here}} ``` This code also sets `s` to `tic-tac-toe`. The `format!` macro works in the same @@ -251,8 +221,7 @@ if you try to access parts of a `String` using indexing syntax in Rust, you’ll get an error. Consider the invalid code in Listing 8-19. ```rust,ignore,does_not_compile -let s1 = String::from("hello"); -let h = s1[0]; +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-19/src/main.rs:here}} ``` Listing 8-19: Attempting to use indexing syntax with a @@ -261,13 +230,7 @@ String This code will result in the following error: ```text -error[E0277]: the trait bound `std::string::String: std::ops::Index<{integer}>` is not satisfied - --> - | -3 | let h = s1[0]; - | ^^^^^ the type `std::string::String` cannot be indexed by `{integer}` - | - = help: the trait `std::ops::Index<{integer}>` is not implemented for `std::string::String` +{{#include ../listings/ch08-common-collections/listing-08-19/output.txt}} ``` The error and the note tell the story: Rust strings don’t support indexing. But @@ -280,7 +243,7 @@ A `String` is a wrapper over a `Vec`. Let’s look at some of our properly encoded UTF-8 example strings from Listing 8-14. First, this one: ```rust -let len = String::from("Hola").len(); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-14/src/main.rs:spanish}} ``` In this case, `len` will be 4, which means the vector storing the string “Hola” @@ -289,7 +252,7 @@ what about the following line? (Note that this string begins with the capital Cyrillic letter Ze, not the Arabic number 3.) ```rust -let len = String::from("Здравствуйте").len(); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-14/src/main.rs:russian}} ``` Asked how long the string is, you might say 12. However, Rust’s answer is 24: @@ -380,7 +343,7 @@ What would happen if we used `&hello[0..1]`? The answer: Rust would panic at runtime in the same way as if an invalid index were accessed in a vector: ```text -thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/libcore/str/mod.rs:2188:4 +{{#include ../listings/ch08-common-collections/output-only-01-not-char-boundary/output.txt}} ``` You should use ranges to create string slices with caution, because doing so diff --git a/src/doc/book/src/ch08-03-hash-maps.md b/src/doc/book/src/ch08-03-hash-maps.md index f140805d71..5abadbd8a5 100644 --- a/src/doc/book/src/ch08-03-hash-maps.md +++ b/src/doc/book/src/ch08-03-hash-maps.md @@ -25,12 +25,7 @@ Blue and Yellow. The Blue team starts with 10 points, and the Yellow team starts with 50. ```rust -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Yellow"), 50); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-20/src/main.rs:here}} ``` Listing 8-20: Creating a new hash map and inserting some @@ -47,21 +42,19 @@ keys of type `String` and values of type `i32`. Like vectors, hash maps are homogeneous: all of the keys must have the same type, and all of the values must have the same type. -Another way of constructing a hash map is by using the `collect` method on a -vector of tuples, where each tuple consists of a key and its value. The -`collect` method gathers data into a number of collection types, including -`HashMap`. For example, if we had the team names and initial scores in two -separate vectors, we could use the `zip` method to create a vector of tuples -where “Blue” is paired with 10, and so forth. Then we could use the `collect` -method to turn that vector of tuples into a hash map, as shown in Listing 8-21. +Another way of constructing a hash map is by using iterators and the `collect` +method on a vector of tuples, where each tuple consists of a key and its value. +We’ll be going into more detail about iterators and their associated methods in +the [”Processing a Series of Items with Iterators” section of Chapter +13][iterators]. The `collect` method gathers data into a number +of collection types, including `HashMap`. For example, if we had the team names +and initial scores in two separate vectors, we could use the `zip` method to +create a vector of tuples where “Blue” is paired with 10, and so forth. Then we +could use the `collect` method to turn that vector of tuples into a hash map, +as shown in Listing 8-21. ```rust -use std::collections::HashMap; - -let teams = vec![String::from("Blue"), String::from("Yellow")]; -let initial_scores = vec![10, 50]; - -let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-21/src/main.rs:here}} ``` Listing 8-21: Creating a hash map from a list of teams @@ -71,7 +64,9 @@ The type annotation `HashMap<_, _>` is needed here because it’s possible to `collect` into many different data structures and Rust doesn’t know which you want unless you specify. For the parameters for the key and value types, however, we use underscores, and Rust can infer the types that the hash map -contains based on the types of the data in the vectors. +contains based on the types of the data in the vectors. In Listing 8-21, the +key type will be `String` and the value type will be `i32`, just as the types +were in Listing 8-20. ### Hash Maps and Ownership @@ -80,15 +75,7 @@ into the hash map. For owned values like `String`, the values will be moved and the hash map will be the owner of those values, as demonstrated in Listing 8-22. ```rust -use std::collections::HashMap; - -let field_name = String::from("Favorite color"); -let field_value = String::from("Blue"); - -let mut map = HashMap::new(); -map.insert(field_name, field_value); -// field_name and field_value are invalid at this point, try using them and -// see what compiler error you get! +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-22/src/main.rs:here}} ``` Listing 8-22: Showing that keys and values are owned by @@ -110,15 +97,7 @@ We can get a value out of the hash map by providing its key to the `get` method, as shown in Listing 8-23. ```rust -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Yellow"), 50); - -let team_name = String::from("Blue"); -let score = scores.get(&team_name); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-23/src/main.rs:here}} ``` Listing 8-23: Accessing the score for the Blue team @@ -134,16 +113,7 @@ We can iterate over each key/value pair in a hash map in a similar manner as we do with vectors, using a `for` loop: ```rust -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Yellow"), 50); - -for (key, value) in &scores { - println!("{}: {}", key, value); -} +{{#rustdoc_include ../listings/ch08-common-collections/no-listing-03-iterate-over-hashmap/src/main.rs:here}} ``` This code will print each pair in an arbitrary order: @@ -173,14 +143,7 @@ only contain one key/value pair because we’re inserting the value for the Blue team’s key both times. ```rust -use std::collections::HashMap; - -let mut scores = HashMap::new(); - -scores.insert(String::from("Blue"), 10); -scores.insert(String::from("Blue"), 25); - -println!("{:?}", scores); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-24/src/main.rs:here}} ``` Listing 8-24: Replacing a value stored with a particular @@ -201,15 +164,7 @@ and the same for the Blue team. Using the `entry` API, the code looks like Listing 8-25. ```rust -use std::collections::HashMap; - -let mut scores = HashMap::new(); -scores.insert(String::from("Blue"), 10); - -scores.entry(String::from("Yellow")).or_insert(50); -scores.entry(String::from("Blue")).or_insert(50); - -println!("{:?}", scores); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-25/src/main.rs:here}} ``` Listing 8-25: Using the `entry` method to only insert if @@ -237,18 +192,7 @@ seen that word. If it’s the first time we’ve seen a word, we’ll first inse the value 0. ```rust -use std::collections::HashMap; - -let text = "hello world wonderful world"; - -let mut map = HashMap::new(); - -for word in text.split_whitespace() { - let count = map.entry(word).or_insert(0); - *count += 1; -} - -println!("{:?}", map); +{{#rustdoc_include ../listings/ch08-common-collections/listing-08-26/src/main.rs:here}} ``` Listing 8-26: Counting occurrences of words using a hash @@ -302,5 +246,6 @@ and hash maps have that will be helpful for these exercises! We’re getting into more complex programs in which operations can fail, so, it’s a perfect time to discuss error handling. We’ll do that next! +[iterators]: ch13-02-iterators.html [validating-references-with-lifetimes]: ch10-03-lifetime-syntax.html#validating-references-with-lifetimes diff --git a/src/doc/book/src/ch09-01-unrecoverable-errors-with-panic.md b/src/doc/book/src/ch09-01-unrecoverable-errors-with-panic.md index 454b78071d..e677281038 100644 --- a/src/doc/book/src/ch09-01-unrecoverable-errors-with-panic.md +++ b/src/doc/book/src/ch09-01-unrecoverable-errors-with-panic.md @@ -29,20 +29,13 @@ Let’s try calling `panic!` in a simple program: Filename: src/main.rs ```rust,should_panic,panics -fn main() { - panic!("crash and burn"); -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-01-panic/src/main.rs}} ``` When you run the program, you’ll see something like this: ```text -$ cargo run - Compiling panic v0.1.0 (file:///projects/panic) - Finished dev [unoptimized + debuginfo] target(s) in 0.25s - Running `target/debug/panic` -thread 'main' panicked at 'crash and burn', src/main.rs:2:5 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch09-error-handling/no-listing-01-panic/output.txt}} ``` The call to `panic!` causes the error message contained in the last two lines. @@ -69,11 +62,7 @@ element by index in a vector. Filename: src/main.rs ```rust,should_panic,panics -fn main() { - let v = vec![1, 2, 3]; - - v[99]; -} +{{#rustdoc_include ../listings/ch09-error-handling/listing-09-01/src/main.rs}} ``` Listing 9-1: Attempting to access an element beyond the @@ -85,25 +74,20 @@ situation, Rust will panic. Using `[]` is supposed to return an element, but if you pass an invalid index, there’s no element that Rust could return here that would be correct. -Other languages, like C, will attempt to give you exactly what you asked for in -this situation, even though it isn’t what you want: you’ll get whatever is at -the location in memory that would correspond to that element in the vector, -even though the memory doesn’t belong to the vector. This is called a *buffer -overread* and can lead to security vulnerabilities if an attacker is able to -manipulate the index in such a way as to read data they shouldn’t be allowed to -that is stored after the array. +In C, attempting to read beyond the end of a data structure is undefined +behavior. You might get whatever is at the location in memory that would +correspond to that element in the data structure, even though the memory +doesn’t belong to that structure. This is called a *buffer overread* and can +lead to security vulnerabilities if an attacker is able to manipulate the index +in such a way as to read data they shouldn’t be allowed to that is stored after +the data structure. To protect your program from this sort of vulnerability, if you try to read an element at an index that doesn’t exist, Rust will stop execution and refuse to continue. Let’s try it and see: ```text -$ cargo run - Compiling panic v0.1.0 (file:///projects/panic) - Finished dev [unoptimized + debuginfo] target(s) in 0.27s - Running `target/debug/panic` -thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', libcore/slice/mod.rs:2448:10 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch09-error-handling/listing-09-01/output.txt}} ``` This error points at a file we didn’t write, *libcore/slice/mod.rs*. That’s the @@ -123,53 +107,69 @@ library code, or crates that you’re using. Let’s try getting a backtrace by setting the `RUST_BACKTRACE` environment variable to any value except 0. Listing 9-2 shows output similar to what you’ll see. + + ```text $ RUST_BACKTRACE=1 cargo run - Finished dev [unoptimized + debuginfo] target(s) in 0.00s - Running `target/debug/panic` -thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', libcore/slice/mod.rs:2448:10 +thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2806:10 stack backtrace: - 0: std::sys::unix::backtrace::tracing::imp::unwind_backtrace - at libstd/sys/unix/backtrace/tracing/gcc_s.rs:49 - 1: std::sys_common::backtrace::print - at libstd/sys_common/backtrace.rs:71 - at libstd/sys_common/backtrace.rs:59 - 2: std::panicking::default_hook::{{closure}} - at libstd/panicking.rs:211 - 3: std::panicking::default_hook - at libstd/panicking.rs:227 - 4: as core::panic::BoxMeUp>::get - at libstd/panicking.rs:476 - 5: std::panicking::continue_panic_fmt - at libstd/panicking.rs:390 - 6: std::panicking::try::do_call - at libstd/panicking.rs:325 - 7: core::ptr::drop_in_place - at libcore/panicking.rs:77 - 8: core::ptr::drop_in_place - at libcore/panicking.rs:59 - 9: >::index - at libcore/slice/mod.rs:2448 - 10: core::slice:: for [T]>::index - at libcore/slice/mod.rs:2316 - 11: as core::ops::index::Index>::index - at liballoc/vec.rs:1653 - 12: panic::main + 0: backtrace::backtrace::libunwind::trace + at /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/libunwind.rs:88 + 1: backtrace::backtrace::trace_unsynchronized + at /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/mod.rs:66 + 2: std::sys_common::backtrace::_print_fmt + at src/libstd/sys_common/backtrace.rs:84 + 3: ::fmt + at src/libstd/sys_common/backtrace.rs:61 + 4: core::fmt::ArgumentV1::show_usize + 5: std::io::Write::write_fmt + at src/libstd/io/mod.rs:1426 + 6: std::sys_common::backtrace::_print + at src/libstd/sys_common/backtrace.rs:65 + 7: std::sys_common::backtrace::print + at src/libstd/sys_common/backtrace.rs:50 + 8: std::panicking::default_hook::{{closure}} + at src/libstd/panicking.rs:193 + 9: std::panicking::default_hook + at src/libstd/panicking.rs:210 + 10: std::panicking::rust_panic_with_hook + at src/libstd/panicking.rs:471 + 11: rust_begin_unwind + at src/libstd/panicking.rs:375 + 12: core::panicking::panic_fmt + at src/libcore/panicking.rs:84 + 13: core::panicking::panic_bounds_check + at src/libcore/panicking.rs:62 + 14: >::index + at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2806 + 15: core::slice:: for [T]>::index + at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libcore/slice/mod.rs:2657 + 16: as core::ops::index::Index>::index + at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/liballoc/vec.rs:1871 + 17: panic::main at src/main.rs:4 - 13: std::rt::lang_start::{{closure}} - at libstd/rt.rs:74 - 14: std::panicking::try::do_call - at libstd/rt.rs:59 - at libstd/panicking.rs:310 - 15: macho_symbol_search - at libpanic_unwind/lib.rs:102 - 16: std::alloc::default_alloc_error_hook - at libstd/panicking.rs:289 - at libstd/panic.rs:392 - at libstd/rt.rs:58 - 17: std::rt::lang_start - at libstd/rt.rs:74 - 18: panic::main + 18: std::rt::lang_start::{{closure}} + at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libstd/rt.rs:67 + 19: std::rt::lang_start_internal::{{closure}} + at src/libstd/rt.rs:52 + 20: std::panicking::try::do_call + at src/libstd/panicking.rs:292 + 21: __rust_maybe_catch_panic + at src/libpanic_unwind/lib.rs:78 + 22: std::panicking::try + at src/libstd/panicking.rs:270 + 23: std::panic::catch_unwind + at src/libstd/panic.rs:394 + 24: std::rt::lang_start_internal + at src/libstd/rt.rs:51 + 25: std::rt::lang_start + at /rustc/5e1a799842ba6ed4a57e91f7ab9435947482f7d8/src/libstd/rt.rs:67 + 26: panic::main ``` Listing 9-2: The backtrace generated by a call to @@ -181,7 +181,7 @@ information, debug symbols must be enabled. Debug symbols are enabled by default when using `cargo build` or `cargo run` without the `--release` flag, as we have here. -In the output in Listing 9-2, line 12 of the backtrace points to the line in +In the output in Listing 9-2, line 17 of the backtrace points to the line in our project that’s causing the problem: line 4 of *src/main.rs*. If we don’t want our program to panic, the location pointed to by the first line mentioning a file we wrote is where we should start investigating. In Listing 9-1, where diff --git a/src/doc/book/src/ch09-02-recoverable-errors-with-result.md b/src/doc/book/src/ch09-02-recoverable-errors-with-result.md index 8461e2bf03..26f9e5120e 100644 --- a/src/doc/book/src/ch09-02-recoverable-errors-with-result.md +++ b/src/doc/book/src/ch09-02-recoverable-errors-with-result.md @@ -34,11 +34,7 @@ fail. In Listing 9-3 we try to open a file. Filename: src/main.rs ```rust -use std::fs::File; - -fn main() { - let f = File::open("hello.txt"); -} +{{#rustdoc_include ../listings/ch09-error-handling/listing-09-03/src/main.rs}} ``` Listing 9-3: Opening a file @@ -52,21 +48,13 @@ type of `f` *is*. Let’s try it! We know that the return type of `File::open` isn’t of type `u32`, so let’s change the `let f` statement to this: ```rust,ignore,does_not_compile -let f: u32 = File::open("hello.txt"); +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/src/main.rs:here}} ``` Attempting to compile now gives us the following output: ```text -error[E0308]: mismatched types - --> src/main.rs:4:18 - | -4 | let f: u32 = File::open("hello.txt"); - | ^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum -`std::result::Result` - | - = note: expected type `u32` - found type `std::result::Result` +{{#include ../listings/ch09-error-handling/no-listing-02-ask-compiler-for-type/output.txt}} ``` This tells us the return type of the `File::open` function is a `Result`. @@ -95,18 +83,7 @@ Chapter 6. Filename: src/main.rs ```rust,should_panic -use std::fs::File; - -fn main() { - let f = File::open("hello.txt"); - - let f = match f { - Ok(file) => file, - Err(error) => { - panic!("Problem opening the file: {:?}", error) - }, - }; -} +{{#rustdoc_include ../listings/ch09-error-handling/listing-09-04/src/main.rs}} ``` Listing 9-4: Using a `match` expression to handle the @@ -127,8 +104,7 @@ there’s no file named *hello.txt* in our current directory and we run this code, we’ll see the following output from the `panic!` macro: ```text -thread 'main' panicked at 'Problem opening the file: Error { repr: -Os { code: 2, message: "No such file or directory" } }', src/main.rs:9:12 +{{#include ../listings/ch09-error-handling/listing-09-04/output.txt}} ``` As usual, this output tells us exactly what has gone wrong. @@ -149,23 +125,7 @@ at Listing 9-5, which adds an inner `match` expression. tests to fail lol --> ```rust,ignore -use std::fs::File; -use std::io::ErrorKind; - -fn main() { - let f = File::open("hello.txt"); - - let f = match f { - Ok(file) => file, - Err(error) => match error.kind() { - ErrorKind::NotFound => match File::create("hello.txt") { - Ok(fc) => fc, - Err(e) => panic!("Problem creating the file: {:?}", e), - }, - other_error => panic!("Problem opening the file: {:?}", other_error), - }, - }; -} +{{#rustdoc_include ../listings/ch09-error-handling/listing-09-05/src/main.rs}} ``` Listing 9-5: Handling different kinds of errors in @@ -195,20 +155,7 @@ E>` type has many methods that accept a closure and are implemented using more seasoned Rustacean might write this code instead of Listing 9-5: ```rust,ignore -use std::fs::File; -use std::io::ErrorKind; - -fn main() { - let f = File::open("hello.txt").unwrap_or_else(|error| { - if error.kind() == ErrorKind::NotFound { - File::create("hello.txt").unwrap_or_else(|error| { - panic!("Problem creating the file: {:?}", error); - }) - } else { - panic!("Problem opening the file: {:?}", error); - } - }); -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-03-closures/src/main.rs}} ``` Although this code has the same behavior as Listing 9-5, it doesn’t contain any @@ -230,11 +177,7 @@ call the `panic!` macro for us. Here is an example of `unwrap` in action: Filename: src/main.rs ```rust,should_panic -use std::fs::File; - -fn main() { - let f = File::open("hello.txt").unwrap(); -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-04-unwrap/src/main.rs}} ``` If we run this code without a *hello.txt* file, we’ll see an error message from @@ -254,11 +197,7 @@ panic easier. The syntax of `expect` looks like this: Filename: src/main.rs ```rust,should_panic -use std::fs::File; - -fn main() { - let f = File::open("hello.txt").expect("Failed to open hello.txt"); -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-05-expect/src/main.rs}} ``` We use `expect` in the same way as `unwrap`: to return the file handle or call @@ -292,26 +231,12 @@ to the code that called this function. Filename: src/main.rs -```rust -use std::io; -use std::io::Read; -use std::fs::File; - -fn read_username_from_file() -> Result { - let f = File::open("hello.txt"); - - let mut f = match f { - Ok(file) => file, - Err(e) => return Err(e), - }; + - let mut s = String::new(); - - match f.read_to_string(&mut s) { - Ok(_) => Ok(s), - Err(e) => Err(e), - } -} +```rust +{{#include ../listings/ch09-error-handling/listing-09-06/src/main.rs:here}} ``` Listing 9-6: A function that returns errors to the @@ -372,17 +297,12 @@ same functionality as it had in Listing 9-6, but this implementation uses the Filename: src/main.rs + + ```rust -use std::io; -use std::io::Read; -use std::fs::File; - -fn read_username_from_file() -> Result { - let mut f = File::open("hello.txt")?; - let mut s = String::new(); - f.read_to_string(&mut s)?; - Ok(s) -} +{{#include ../listings/ch09-error-handling/listing-09-07/src/main.rs:here}} ``` Listing 9-7: A function that returns errors to the @@ -420,18 +340,12 @@ method calls immediately after the `?`, as shown in Listing 9-8. Filename: src/main.rs -```rust -use std::io; -use std::io::Read; -use std::fs::File; - -fn read_username_from_file() -> Result { - let mut s = String::new(); - - File::open("hello.txt")?.read_to_string(&mut s)?; + - Ok(s) -} +```rust +{{#include ../listings/ch09-error-handling/listing-09-08/src/main.rs:here}} ``` Listing 9-8: Chaining method calls after the `?` @@ -451,13 +365,12 @@ there’s a way to make this even shorter. Filename: src/main.rs -```rust -use std::io; -use std::fs; + -fn read_username_from_file() -> Result { - fs::read_to_string("hello.txt") -} +```rust +{{#include ../listings/ch09-error-handling/listing-09-09/src/main.rs:here}} ``` Listing 9-9: Using `fs::read_to_string` instead of @@ -482,26 +395,13 @@ Let’s look at what happens if we use the `?` operator in the `main` function, which you’ll recall has a return type of `()`: ```rust,ignore,does_not_compile -use std::fs::File; - -fn main() { - let f = File::open("hello.txt")?; -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-06-question-mark-in-main/src/main.rs}} ``` When we compile this code, we get the following error message: ```text -error[E0277]: the `?` operator can only be used in a function that returns -`Result` or `Option` (or another type that implements `std::ops::Try`) - --> src/main.rs:4:13 - | -4 | let f = File::open("hello.txt")?; - | ^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a - function that returns `()` - | - = help: the trait `std::ops::Try` is not implemented for `()` - = note: required by `std::ops::Try::from_error` +{{#include ../listings/ch09-error-handling/no-listing-06-question-mark-in-main/output.txt}} ``` This error points out that we’re only allowed to use the `?` operator in a @@ -519,14 +419,7 @@ type must be. One valid return type for main is `()`, and conveniently, another valid return type is `Result`, as shown here: ```rust,ignore -use std::error::Error; -use std::fs::File; - -fn main() -> Result<(), Box> { - let f = File::open("hello.txt")?; - - Ok(()) -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-07-main-returning-result/src/main.rs}} ``` The `Box` type is called a trait object, which we’ll talk about in diff --git a/src/doc/book/src/ch09-03-to-panic-or-not-to-panic.md b/src/doc/book/src/ch09-03-to-panic-or-not-to-panic.md index a8f6965b1f..e5af81d0eb 100644 --- a/src/doc/book/src/ch09-03-to-panic-or-not-to-panic.md +++ b/src/doc/book/src/ch09-03-to-panic-or-not-to-panic.md @@ -48,9 +48,7 @@ have an `Err` variant, it’s perfectly acceptable to call `unwrap`. Here’s an example: ```rust -use std::net::IpAddr; - -let home: IpAddr = "127.0.0.1".parse().unwrap(); +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs:here}} ``` We’re creating an `IpAddr` instance by parsing a hardcoded string. We can see @@ -133,22 +131,7 @@ One way to do this would be to parse the guess as an `i32` instead of only a number being in range, like so: ```rust,ignore -loop { - // --snip-- - - let guess: i32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, - }; - - if guess < 1 || guess > 100 { - println!("The secret number will be between 1 and 100."); - continue; - } - - match guess.cmp(&secret_number) { - // --snip-- -} +{{#rustdoc_include ../listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs:here}} ``` The `if` expression checks whether our value is out of range, tells the user @@ -169,26 +152,13 @@ confidently use the values they receive. Listing 9-10 shows one way to define a `Guess` type that will only create an instance of `Guess` if the `new` function receives a value between 1 and 100. + + ```rust -pub struct Guess { - value: i32, -} - -impl Guess { - pub fn new(value: i32) -> Guess { - if value < 1 || value > 100 { - panic!("Guess value must be between 1 and 100, got {}.", value); - } - - Guess { - value - } - } - - pub fn value(&self) -> i32 { - self.value - } -} +{{#include ../listings/ch09-error-handling/listing-09-10/src/main.rs:here}} ``` Listing 9-10: A `Guess` type that will only continue with diff --git a/src/doc/book/src/ch10-00-generics.md b/src/doc/book/src/ch10-00-generics.md index b411210be2..032f4374bc 100644 --- a/src/doc/book/src/ch10-00-generics.md +++ b/src/doc/book/src/ch10-00-generics.md @@ -41,20 +41,7 @@ Listing 10-1. Filename: src/main.rs ```rust -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let mut largest = number_list[0]; - - for number in number_list { - if number > largest { - largest = number; - } - } - - println!("The largest number is {}", largest); -# assert_eq!(largest, 100); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-01/src/main.rs:here}} ``` Listing 10-1: Code to find the largest number in a list @@ -76,31 +63,7 @@ program, as shown in Listing 10-2. Filename: src/main.rs ```rust -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let mut largest = number_list[0]; - - for number in number_list { - if number > largest { - largest = number; - } - } - - println!("The largest number is {}", largest); - - let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; - - let mut largest = number_list[0]; - - for number in number_list { - if number > largest { - largest = number; - } - } - - println!("The largest number is {}", largest); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-02/src/main.rs}} ``` Listing 10-2: Code to find the largest number in *two* @@ -122,31 +85,7 @@ number in two different lists. Filename: src/main.rs ```rust -fn largest(list: &[i32]) -> i32 { - let mut largest = list[0]; - - for &item in list { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest(&number_list); - println!("The largest number is {}", result); -# assert_eq!(result, 100); - - let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; - - let result = largest(&number_list); - println!("The largest number is {}", result); -# assert_eq!(result, 6000); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-03/src/main.rs:here}} ``` Listing 10-3: Abstracted code to find the largest number diff --git a/src/doc/book/src/ch10-01-syntax.md b/src/doc/book/src/ch10-01-syntax.md index f69165e269..3d86ebfa16 100644 --- a/src/doc/book/src/ch10-01-syntax.md +++ b/src/doc/book/src/ch10-01-syntax.md @@ -18,43 +18,7 @@ both find the largest value in a slice. Filename: src/main.rs ```rust -fn largest_i32(list: &[i32]) -> i32 { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn largest_char(list: &[char]) -> char { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest_i32(&number_list); - println!("The largest number is {}", result); -# assert_eq!(result, 100); - - let char_list = vec!['y', 'm', 'a', 'q']; - - let result = largest_char(&char_list); - println!("The largest char is {}", result); -# assert_eq!(result, 'y'); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-04/src/main.rs:here}} ``` Listing 10-4: Two functions that differ only in their @@ -95,29 +59,7 @@ compile yet, but we’ll fix it later in this chapter. Filename: src/main.rs ```rust,ignore,does_not_compile -fn largest(list: &[T]) -> T { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest(&number_list); - println!("The largest number is {}", result); - - let char_list = vec!['y', 'm', 'a', 'q']; - - let result = largest(&char_list); - println!("The largest char is {}", result); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/src/main.rs}} ``` Listing 10-5: A definition of the `largest` function that @@ -126,13 +68,7 @@ uses generic type parameters but doesn’t compile yet If we compile this code right now, we’ll get this error: ```text -error[E0369]: binary operation `>` cannot be applied to type `T` - --> src/main.rs:5:12 - | -5 | if item > largest { - | ^^^^^^^^^^^^^^ - | - = note: an implementation of `std::cmp::PartialOrd` might be missing for `T` +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt}} ``` The note mentions `std::cmp::PartialOrd`, which is a *trait*. We’ll talk about @@ -155,15 +91,7 @@ struct to hold `x` and `y` coordinate values of any type. Filename: src/main.rs ```rust -struct Point { - x: T, - y: T, -} - -fn main() { - let integer = Point { x: 5, y: 10 }; - let float = Point { x: 1.0, y: 4.0 }; -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-06/src/main.rs}} ``` Listing 10-6: A `Point` struct that holds `x` and `y` @@ -184,14 +112,7 @@ Listing 10-7, our code won’t compile. Filename: src/main.rs ```rust,ignore,does_not_compile -struct Point { - x: T, - y: T, -} - -fn main() { - let wont_work = Point { x: 5, y: 4.0 }; -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/src/main.rs}} ``` Listing 10-7: The fields `x` and `y` must be the same @@ -203,15 +124,7 @@ compiler know that the generic type `T` will be an integer for this instance of same type as `x`, we’ll get a type mismatch error like this: ```text -error[E0308]: mismatched types - --> src/main.rs:7:38 - | -7 | let wont_work = Point { x: 5, y: 4.0 }; - | ^^^ expected integer, found -floating-point number - | - = note: expected type `{integer}` - found type `{float}` +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-07/output.txt}} ``` To define a `Point` struct where `x` and `y` are both generics but could have @@ -222,16 +135,7 @@ Listing 10-8, we can change the definition of `Point` to be generic over types Filename: src/main.rs ```rust -struct Point { - x: T, - y: U, -} - -fn main() { - let both_integer = Point { x: 5, y: 10 }; - let both_float = Point { x: 1.0, y: 4.0 }; - let integer_and_float = Point { x: 5, y: 4.0 }; -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-08/src/main.rs}} ``` Listing 10-8: A `Point` generic over two types so @@ -294,22 +198,7 @@ struct we defined in Listing 10-6 with a method named `x` implemented on it. Filename: src/main.rs ```rust -struct Point { - x: T, - y: T, -} - -impl Point { - fn x(&self) -> &T { - &self.x - } -} - -fn main() { - let p = Point { x: 5, y: 10 }; - - println!("p.x = {}", p.x()); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-09/src/main.rs}} ``` Listing 10-9: Implementing a method named `x` on the @@ -328,17 +217,10 @@ We could, for example, implement methods only on `Point` instances rather than on `Point` instances with any generic type. In Listing 10-10 we use the concrete type `f32`, meaning we don’t declare any types after `impl`. +Filename: src/main.rs + ```rust -# struct Point { -# x: T, -# y: T, -# } -# -impl Point { - fn distance_from_origin(&self) -> f32 { - (self.x.powi(2) + self.y.powi(2)).sqrt() - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-10/src/main.rs:here}} ``` Listing 10-10: An `impl` block that only applies to a @@ -361,28 +243,7 @@ value from the passed-in `Point` (of type `W`). Filename: src/main.rs ```rust -struct Point { - x: T, - y: U, -} - -impl Point { - fn mixup(self, other: Point) -> Point { - Point { - x: self.x, - y: other.y, - } - } -} - -fn main() { - let p1 = Point { x: 5, y: 10.4 }; - let p2 = Point { x: "Hello", y: 'c'}; - - let p3 = p1.mixup(p2); - - println!("p3.x = {}, p3.y = {}", p3.x, p3.y); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-11/src/main.rs}} ``` Listing 10-11: A method that uses different generic types diff --git a/src/doc/book/src/ch10-02-traits.md b/src/doc/book/src/ch10-02-traits.md index 19e873bbac..0e01361d22 100644 --- a/src/doc/book/src/ch10-02-traits.md +++ b/src/doc/book/src/ch10-02-traits.md @@ -30,9 +30,7 @@ need a summary from each type, and we need to request that summary by calling a Filename: src/lib.rs ```rust -pub trait Summary { - fn summarize(&self) -> String; -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-12/src/lib.rs}} ``` Listing 10-12: A `Summary` trait that consists of the @@ -65,35 +63,7 @@ already limited to 280 characters. Filename: src/lib.rs ```rust -# pub trait Summary { -# fn summarize(&self) -> String; -# } -# -pub struct NewsArticle { - pub headline: String, - pub location: String, - pub author: String, - pub content: String, -} - -impl Summary for NewsArticle { - fn summarize(&self) -> String { - format!("{}, by {} ({})", self.headline, self.author, self.location) - } -} - -pub struct Tweet { - pub username: String, - pub content: String, - pub reply: bool, - pub retweet: bool, -} - -impl Summary for Tweet { - fn summarize(&self) -> String { - format!("{}: {}", self.username, self.content) - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-13/src/lib.rs:here}} ``` Listing 10-13: Implementing the `Summary` trait on the @@ -112,14 +82,7 @@ After implementing the trait, we can call the methods on instances of `NewsArticle` and `Tweet` in the same way we call regular methods, like this: ```rust,ignore -let tweet = Tweet { - username: String::from("horse_ebooks"), - content: String::from("of course, as you probably already know, people"), - reply: false, - retweet: false, -}; - -println!("1 new tweet: {}", tweet.summarize()); +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-01-calling-trait-method/src/main.rs:here}} ``` This code prints `1 new tweet: horse_ebooks: of course, as you probably already @@ -168,11 +131,7 @@ in Listing 10-12. Filename: src/lib.rs ```rust -pub trait Summary { - fn summarize(&self) -> String { - String::from("(Read more...)") - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-14/src/lib.rs:here}} ``` Listing 10-14: Definition of a `Summary` trait with a @@ -188,15 +147,7 @@ directly, we’ve provided a default implementation and specified that the `summarize` method on an instance of `NewsArticle`, like this: ```rust,ignore -let article = NewsArticle { - headline: String::from("Penguins win the Stanley Cup Championship!"), - location: String::from("Pittsburgh, PA, USA"), - author: String::from("Iceburgh"), - content: String::from("The Pittsburgh Penguins once again are the best - hockey team in the NHL."), -}; - -println!("New article available! {}", article.summarize()); +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-02-calling-default-impl/src/main.rs:here}} ``` This code prints `New article available! (Read more...)`. @@ -216,24 +167,14 @@ a small part of it. For example, we could define the `Summary` trait to have a `summarize_author` method: ```rust -pub trait Summary { - fn summarize_author(&self) -> String; - - fn summarize(&self) -> String { - format!("(Read more from {}...)", self.summarize_author()) - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs:here}} ``` To use this version of `Summary`, we only need to define `summarize_author` when we implement the trait on a type: ```rust,ignore -impl Summary for Tweet { - fn summarize_author(&self) -> String { - format!("@{}", self.username) - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/lib.rs:impl}} ``` After we define `summarize_author`, we can call `summarize` on instances of the @@ -243,14 +184,7 @@ definition of `summarize_author` that we’ve provided. Because we’ve implemen `summarize` method without requiring us to write any more code. ```rust,ignore -let tweet = Tweet { - username: String::from("horse_ebooks"), - content: String::from("of course, as you probably already know, people"), - reply: false, - retweet: false, -}; - -println!("1 new tweet: {}", tweet.summarize()); +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-03-default-impl-calls-other-methods/src/main.rs:here}} ``` This code prints `1 new tweet: (Read more from @horse_ebooks...)`. @@ -270,9 +204,7 @@ implements the `Summary` trait. To do this, we can use the `impl Trait` syntax, like this: ```rust,ignore -pub fn notify(item: impl Summary) { - println!("Breaking news! {}", item.summarize()); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-04-traits-as-parameters/src/lib.rs:here}} ``` Instead of a concrete type for the `item` parameter, we specify the `impl` @@ -373,14 +305,7 @@ We can also use the `impl Trait` syntax in the return position to return a value of some type that implements a trait, as shown here: ```rust,ignore -fn returns_summarizable() -> impl Summary { - Tweet { - username: String::from("horse_ebooks"), - content: String::from("of course, as you probably already know, people"), - reply: false, - retweet: false, - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-05-returning-impl-trait/src/lib.rs:here}} ``` By using `impl Summary` for the return type, we specify that the @@ -400,24 +325,7 @@ example, this code that returns either a `NewsArticle` or a `Tweet` with the return type specified as `impl Summary` wouldn’t work: ```rust,ignore,does_not_compile -fn returns_summarizable(switch: bool) -> impl Summary { - if switch { - NewsArticle { - headline: String::from("Penguins win the Stanley Cup Championship!"), - location: String::from("Pittsburgh, PA, USA"), - author: String::from("Iceburgh"), - content: String::from("The Pittsburgh Penguins once again are the best - hockey team in the NHL."), - } - } else { - Tweet { - username: String::from("horse_ebooks"), - content: String::from("of course, as you probably already know, people"), - reply: false, - retweet: false, - } - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-06-impl-trait-returns-one-type/src/lib.rs:here}} ``` Returning either a `NewsArticle` or a `Tweet` isn’t allowed due to restrictions @@ -435,13 +343,7 @@ the `largest` function that uses a generic type parameter! Last time we tried to run that code, we received this error: ```text -error[E0369]: binary operation `>` cannot be applied to type `T` - --> src/main.rs:5:12 - | -5 | if item > largest { - | ^^^^^^^^^^^^^^ - | - = note: an implementation of `std::cmp::PartialOrd` might be missing for `T` +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-05/output.txt}} ``` In the body of `largest` we wanted to compare two values of type `T` using the @@ -453,29 +355,13 @@ into scope because it’s in the prelude. Change the signature of `largest` to look like this: ```rust,ignore -fn largest(list: &[T]) -> T { +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/src/main.rs:here}} ``` This time when we compile the code, we get a different set of errors: ```text -error[E0508]: cannot move out of type `[T]`, a non-copy slice - --> src/main.rs:2:23 - | -2 | let mut largest = list[0]; - | ^^^^^^^ - | | - | cannot move out of here - | help: consider using a reference instead: `&list[0]` - -error[E0507]: cannot move out of borrowed content - --> src/main.rs:4:9 - | -4 | for &item in list.iter() { - | ^---- - | || - | |hint: to prevent move, use `ref item` or `ref mut item` - | cannot move out of borrowed content +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-07-fixing-listing-10-05/output.txt}} ``` The key line in this error is `cannot move out of type [T], a non-copy slice`. @@ -498,29 +384,7 @@ values in the slice that we pass into the function implement the `PartialOrd` Filename: src/main.rs ```rust -fn largest(list: &[T]) -> T { - let mut largest = list[0]; - - for &item in list.iter() { - if item > largest { - largest = item; - } - } - - largest -} - -fn main() { - let number_list = vec![34, 50, 25, 100, 65]; - - let result = largest(&number_list); - println!("The largest number is {}", result); - - let char_list = vec!['y', 'm', 'a', 'q']; - - let result = largest(&char_list); - println!("The largest char is {}", result); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-15/src/main.rs}} ``` Listing 10-15: A working definition of the `largest` @@ -550,32 +414,10 @@ traits. For example, the type `Pair` in Listing 10-16 always implements the inner type `T` implements the `PartialOrd` trait that enables comparison *and* the `Display` trait that enables printing. -```rust -use std::fmt::Display; - -struct Pair { - x: T, - y: T, -} - -impl Pair { - fn new(x: T, y: T) -> Self { - Self { - x, - y, - } - } -} +Filename: src/lib.rs -impl Pair { - fn cmp_display(&self) { - if self.x >= self.y { - println!("The largest member is x = {}", self.x); - } else { - println!("The largest member is y = {}", self.y); - } - } -} +```rust +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-16/src/lib.rs}} ``` Listing 10-16: Conditionally implement methods on a diff --git a/src/doc/book/src/ch10-03-lifetime-syntax.md b/src/doc/book/src/ch10-03-lifetime-syntax.md index 383a4ec40e..c00703946e 100644 --- a/src/doc/book/src/ch10-03-lifetime-syntax.md +++ b/src/doc/book/src/ch10-03-lifetime-syntax.md @@ -25,16 +25,7 @@ Consider the program in Listing 10-17, which has an outer scope and an inner scope. ```rust,ignore,does_not_compile -{ - let r; - - { - let x = 5; - r = &x; - } - - println!("r: {}", r); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs:here}} ``` Listing 10-17: An attempt to use a reference whose value @@ -55,16 +46,7 @@ compile because the value `r` is referring to has gone out of scope before we try to use it. Here is the error message: ```text -error[E0597]: `x` does not live long enough - --> src/main.rs:7:5 - | -6 | r = &x; - | - borrow occurs here -7 | } - | ^ `x` dropped here while still borrowed -... -10 | } - | - borrowed value needs to live until here +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt}} ``` The variable `x` doesn’t “live long enough.” The reason is that `x` will be out @@ -82,16 +64,7 @@ whether all borrows are valid. Listing 10-18 shows the same code as Listing 10-17 but with annotations showing the lifetimes of the variables. ```rust,ignore,does_not_compile -{ - let r; // ---------+-- 'a - // | - { // | - let x = 5; // -+-- 'b | - r = &x; // | | - } // -+ | - // | - println!("r: {}", r); // | -} // ---------+ +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs:here}} ``` Listing 10-18: Annotations of the lifetimes of `r` and @@ -108,14 +81,7 @@ Listing 10-19 fixes the code so it doesn’t have a dangling reference and compiles without any errors. ```rust -{ - let x = 5; // ----------+-- 'b - // | - let r = &x; // --+-- 'a | - // | | - println!("r: {}", r); // | | - // --+ | -} // ----------+ +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs:here}} ``` Listing 10-19: A valid reference because the data has a @@ -139,13 +105,7 @@ longest string is abcd`. Filename: src/main.rs ```rust,ignore -fn main() { - let string1 = String::from("abcd"); - let string2 = "xyz"; - - let result = longest(string1.as_str(), string2); - println!("The longest string is {}", result); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs}} ``` Listing 10-20: A `main` function that calls the `longest` @@ -167,13 +127,7 @@ won’t compile. Filename: src/main.rs ```rust,ignore,does_not_compile -fn longest(x: &str, y: &str) -> &str { - if x.len() > y.len() { - x - } else { - y - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs:here}} ``` Listing 10-21: An implementation of the `longest` @@ -183,14 +137,7 @@ compile Instead, we get the following error that talks about lifetimes: ```text -error[E0106]: missing lifetime specifier - --> src/main.rs:1:33 - | -1 | fn longest(x: &str, y: &str) -> &str { - | ^ expected lifetime parameter - | - = help: this function's return type contains a borrowed value, but the -signature does not say whether it is borrowed from `x` or `y` +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt}} ``` The help text reveals that the return type needs a generic lifetime parameter @@ -257,13 +204,7 @@ Listing 10-22. Filename: src/main.rs ```rust -fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { - if x.len() > y.len() { - x - } else { - y - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs:here}} ``` Listing 10-22: The `longest` function definition @@ -310,23 +251,7 @@ a straightforward example. Filename: src/main.rs ```rust -# fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { -# if x.len() > y.len() { -# x -# } else { -# y -# } -# } -# -fn main() { - let string1 = String::from("long string is long"); - - { - let string2 = String::from("xyz"); - let result = longest(string1.as_str(), string2.as_str()); - println!("The longest string is {}", result); - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs:here}} ``` Listing 10-23: Using the `longest` function with @@ -349,15 +274,7 @@ compile. Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let string1 = String::from("long string is long"); - let result; - { - let string2 = String::from("xyz"); - result = longest(string1.as_str(), string2.as_str()); - } - println!("The longest string is {}", result); -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs:here}} ``` Listing 10-24: Attempting to use `result` after `string2` @@ -366,16 +283,7 @@ has gone out of scope When we try to compile this code, we’ll get this error: ```text -error[E0597]: `string2` does not live long enough - --> src/main.rs:15:5 - | -14 | result = longest(string1.as_str(), string2.as_str()); - | ------- borrow occurs here -15 | } - | ^ `string2` dropped here while still borrowed -16 | println!("The longest string is {}", result); -17 | } - | - borrowed value needs to live until here +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt}} ``` The error shows that for `result` to be valid for the `println!` statement, @@ -408,9 +316,7 @@ following code will compile: Filename: src/main.rs ```rust -fn longest<'a>(x: &'a str, y: &str) -> &'a str { - x -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs:here}} ``` In this example, we’ve specified a lifetime parameter `'a` for the parameter @@ -427,10 +333,7 @@ this attempted implementation of the `longest` function that won’t compile: Filename: src/main.rs ```rust,ignore,does_not_compile -fn longest<'a>(x: &str, y: &str) -> &'a str { - let result = String::from("really long string"); - result.as_str() -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs:here}} ``` Here, even though we’ve specified a lifetime parameter `'a` for the return @@ -439,23 +342,7 @@ lifetime is not related to the lifetime of the parameters at all. Here is the error message we get: ```text -error[E0597]: `result` does not live long enough - --> src/main.rs:3:5 - | -3 | result.as_str() - | ^^^^^^ does not live long enough -4 | } - | - borrowed value only lives until here - | -note: borrowed value must be valid for the lifetime 'a as defined on the -function body at 1:1... - --> src/main.rs:1:1 - | -1 | / fn longest<'a>(x: &str, y: &str) -> &'a str { -2 | | let result = String::from("really long string"); -3 | | result.as_str() -4 | | } - | |_^ +{{#include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt}} ``` The problem is that `result` goes out of scope and gets cleaned up at the end @@ -481,17 +368,7 @@ struct named `ImportantExcerpt` that holds a string slice. Filename: src/main.rs ```rust -struct ImportantExcerpt<'a> { - part: &'a str, -} - -fn main() { - let novel = String::from("Call me Ishmael. Some years ago..."); - let first_sentence = novel.split('.') - .next() - .expect("Could not find a '.'"); - let i = ImportantExcerpt { part: first_sentence }; -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs}} ``` Listing 10-25: A struct that holds a reference, so its @@ -521,17 +398,7 @@ Chapter 4 we had a function in Listing 4-9, which is shown again in Listing Filename: src/lib.rs ```rust -fn first_word(s: &str) -> &str { - let bytes = s.as_bytes(); - - for (i, &item) in bytes.iter().enumerate() { - if item == b' ' { - return &s[0..i]; - } - } - - &s[..] -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs:here}} ``` Listing 10-26: A function we defined in Listing 4-9 that @@ -671,15 +538,7 @@ First, we’ll use a method named `level` whose only parameter is a reference to `self` and whose return value is an `i32`, which is not a reference to anything: ```rust -# struct ImportantExcerpt<'a> { -# part: &'a str, -# } -# -impl<'a> ImportantExcerpt<'a> { - fn level(&self) -> i32 { - 3 - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs:1st}} ``` The lifetime parameter declaration after `impl` and its use after the type name @@ -689,16 +548,7 @@ to `self` because of the first elision rule. Here is an example where the third lifetime elision rule applies: ```rust -# struct ImportantExcerpt<'a> { -# part: &'a str, -# } -# -impl<'a> ImportantExcerpt<'a> { - fn announce_and_return_part(&self, announcement: &str) -> &str { - println!("Attention please: {}", announcement); - self.part - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs:3rd}} ``` There are two input lifetimes, so Rust applies the first lifetime elision rule @@ -734,18 +584,7 @@ Let’s briefly look at the syntax of specifying generic type parameters, trait bounds, and lifetimes all in one function! ```rust -use std::fmt::Display; - -fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str - where T: Display -{ - println!("Announcement! {}", ann); - if x.len() > y.len() { - x - } else { - y - } -} +{{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs:here}} ``` This is the `longest` function from Listing 10-22 that returns the longer of diff --git a/src/doc/book/src/ch11-01-writing-tests.md b/src/doc/book/src/ch11-01-writing-tests.md index 42a5391878..a2f62ce4bd 100644 --- a/src/doc/book/src/ch11-01-writing-tests.md +++ b/src/doc/book/src/ch11-01-writing-tests.md @@ -47,14 +47,7 @@ Listing 11-1. Filename: src/lib.rs ```rust -# fn main() {} -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs:here}} ``` Listing 11-1: The test module and function generated @@ -75,21 +68,7 @@ The `cargo test` command runs all tests in our project, as shown in Listing 11-2. ```text -$ cargo test - Compiling adder v0.1.0 (file:///projects/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.22 secs - Running target/debug/deps/adder-ce99bcc2479f4607 - -running 1 test -test tests::it_works ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-01/output.txt}} ``` Listing 11-2: The output from running the automatically @@ -129,24 +108,14 @@ so: Filename: src/lib.rs ```rust -# fn main() {} -#[cfg(test)] -mod tests { - #[test] - fn exploration() { - assert_eq!(2 + 2, 4); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/src/lib.rs:here}} ``` Then run `cargo test` again. The output now shows `exploration` instead of `it_works`: ```text -running 1 test -test tests::exploration ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-01-changing-test-name/output.txt}} ``` Let’s add another test, but this time we’ll make a test that fails! Tests fail @@ -159,19 +128,7 @@ which is to call the `panic!` macro. Enter the new test, `another`, so your Filename: src/lib.rs ```rust,panics -# fn main() {} -#[cfg(test)] -mod tests { - #[test] - fn exploration() { - assert_eq!(2 + 2, 4); - } - - #[test] - fn another() { - panic!("Make this test fail"); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-03/src/lib.rs:here}} ``` Listing 11-3: Adding a second test that will fail because @@ -181,22 +138,7 @@ Run the tests again using `cargo test`. The output should look like Listing 11-4, which shows that our `exploration` test passed and `another` failed. ```text -running 2 tests -test tests::exploration ... ok -test tests::another ... FAILED - -failures: - ----- tests::another stdout ---- -thread 'tests::another' panicked at 'Make this test fail', src/lib.rs:10:9 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::another - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out - -error: test failed +{{#include ../listings/ch11-writing-automated-tests/listing-11-03/output.txt}} ``` Listing 11-4: Test results when one test passes and one @@ -236,18 +178,7 @@ method, which are repeated here in Listing 11-5. Let’s put this code in the Filename: src/lib.rs ```rust -# fn main() {} -#[derive(Debug)] -struct Rectangle { - width: u32, - height: u32, -} - -impl Rectangle { - fn can_hold(&self, other: &Rectangle) -> bool { - self.width > other.width && self.height > other.height - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-05/src/lib.rs:here}} ``` Listing 11-5: Using the `Rectangle` struct and its @@ -262,19 +193,7 @@ has a width of 5 and a height of 1. Filename: src/lib.rs ```rust -# fn main() {} -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn larger_can_hold_smaller() { - let larger = Rectangle { width: 8, height: 7 }; - let smaller = Rectangle { width: 5, height: 1 }; - - assert!(larger.can_hold(&smaller)); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-06/src/lib.rs:here}} ``` Listing 11-6: A test for `can_hold` that checks whether a @@ -295,10 +214,7 @@ passed it the result of calling `larger.can_hold(&smaller)`. This expression is supposed to return `true`, so our test should pass. Let’s find out! ```text -running 1 test -test tests::larger_can_hold_smaller ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-06/output.txt}} ``` It does pass! Let’s add another test, this time asserting that a smaller @@ -307,24 +223,7 @@ rectangle cannot hold a larger rectangle: Filename: src/lib.rs ```rust -# fn main() {} -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn larger_can_hold_smaller() { - // --snip-- - } - - #[test] - fn smaller_cannot_hold_larger() { - let larger = Rectangle { width: 8, height: 7 }; - let smaller = Rectangle { width: 5, height: 1 }; - - assert!(!smaller.can_hold(&larger)); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/src/lib.rs:here}} ``` Because the correct result of the `can_hold` function in this case is `false`, @@ -332,11 +231,7 @@ we need to negate that result before we pass it to the `assert!` macro. As a result, our test will pass if `can_hold` returns `false`: ```text -running 2 tests -test tests::smaller_cannot_hold_larger ... ok -test tests::larger_can_hold_smaller ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-02-adding-another-rectangle-test/output.txt}} ``` Two tests that pass! Now let’s see what happens to our test results when we @@ -345,39 +240,13 @@ method by replacing the greater than sign with a less than sign when it compares the widths: ```rust,not_desired_behavior -# fn main() {} -# #[derive(Debug)] -# struct Rectangle { -# width: u32, -# height: u32, -# } -// --snip-- - -impl Rectangle { - fn can_hold(&self, other: &Rectangle) -> bool { - self.width < other.width && self.height > other.height - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/src/lib.rs:here}} ``` Running the tests now produces the following: ```text -running 2 tests -test tests::smaller_cannot_hold_larger ... ok -test tests::larger_can_hold_smaller ... FAILED - -failures: - ----- tests::larger_can_hold_smaller stdout ---- -thread 'tests::larger_can_hold_smaller' panicked at 'assertion failed: -larger.can_hold(&smaller)', src/lib.rs:22:9 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::larger_can_hold_smaller - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-03-introducing-a-bug/output.txt}} ``` Our tests caught the bug! Because `larger.width` is 8 and `smaller.width` is @@ -404,20 +273,7 @@ parameter and returns the result. Then we test this function using the Filename: src/lib.rs ```rust -# fn main() {} -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_adds_two() { - assert_eq!(4, add_two(2)); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-07/src/lib.rs:here}} ``` Listing 11-7: Testing the function `add_two` using the @@ -426,10 +282,7 @@ mod tests { Let’s check that it passes! ```text -running 1 test -test tests::it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-07/output.txt}} ``` The first argument we gave to the `assert_eq!` macro, `4`, is equal to the @@ -441,30 +294,13 @@ uses `assert_eq!` fails. Change the implementation of the `add_two` function to instead add `3`: ```rust,not_desired_behavior -# fn main() {} -pub fn add_two(a: i32) -> i32 { - a + 3 -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/src/lib.rs:here}} ``` Run the tests again: ```text -running 1 test -test tests::it_adds_two ... FAILED - -failures: - ----- tests::it_adds_two stdout ---- -thread 'tests::it_adds_two' panicked at 'assertion failed: `(left == right)` - left: `4`, - right: `5`', src/lib.rs:11:9 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::it_adds_two - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-04-bug-in-add-two/output.txt}} ``` Our test caught the bug! The `it_adds_two` test failed, displaying the message @@ -523,21 +359,7 @@ want to test that the name we pass into the function appears in the output: Filename: src/lib.rs ```rust -# fn main() {} -pub fn greeting(name: &str) -> String { - format!("Hello {}!", name) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn greeting_contains_name() { - let result = greeting("Carol"); - assert!(result.contains("Carol")); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-05-greeter/src/lib.rs:here}} ``` The requirements for this program haven’t been agreed upon yet, and we’re @@ -551,27 +373,13 @@ Let’s introduce a bug into this code by changing `greeting` to not include `name` to see what this test failure looks like: ```rust,not_desired_behavior -# fn main() {} -pub fn greeting(name: &str) -> String { - String::from("Hello!") -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/src/lib.rs:here}} ``` Running this test produces the following: ```text -running 1 test -test tests::greeting_contains_name ... FAILED - -failures: - ----- tests::greeting_contains_name stdout ---- -thread 'tests::greeting_contains_name' panicked at 'assertion failed: -result.contains("Carol")', src/lib.rs:12:9 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::greeting_contains_name +{{#include ../listings/ch11-writing-automated-tests/no-listing-06-greeter-with-bug/output.txt}} ``` This result just indicates that the assertion failed and which line the @@ -581,23 +389,13 @@ giving it a custom failure message made from a format string with a placeholder filled in with the actual value we got from the `greeting` function: ```rust,ignore -#[test] -fn greeting_contains_name() { - let result = greeting("Carol"); - assert!( - result.contains("Carol"), - "Greeting did not contain name, value was `{}`", result - ); -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/src/lib.rs:here}} ``` Now when we run the test, we’ll get a more informative error message: ```text ----- tests::greeting_contains_name stdout ---- -thread 'tests::greeting_contains_name' panicked at 'Greeting did not -contain name, value was `Hello!`', src/lib.rs:12:9 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch11-writing-automated-tests/no-listing-07-custom-failure-message/output.txt}} ``` We can see the value we actually got in the test output, which would help us @@ -623,33 +421,7 @@ happen when we expect them to. Filename: src/lib.rs ```rust -# fn main() {} -pub struct Guess { - value: i32, -} - -impl Guess { - pub fn new(value: i32) -> Guess { - if value < 1 || value > 100 { - panic!("Guess value must be between 1 and 100, got {}.", value); - } - - Guess { - value - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - #[should_panic] - fn greater_than_100() { - Guess::new(200); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-08/src/lib.rs:here}} ``` Listing 11-8: Testing that a condition will cause a @@ -660,48 +432,20 @@ before the test function it applies to. Let’s look at the result when this tes passes: ```text -running 1 test -test tests::greater_than_100 ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-08/output.txt}} ``` Looks good! Now let’s introduce a bug in our code by removing the condition that the `new` function will panic if the value is greater than 100: ```rust,not_desired_behavior -# fn main() {} -# pub struct Guess { -# value: i32, -# } -# -// --snip-- - -impl Guess { - pub fn new(value: i32) -> Guess { - if value < 1 { - panic!("Guess value must be between 1 and 100, got {}.", value); - } - - Guess { - value - } - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/src/lib.rs:here}} ``` When we run the test in Listing 11-8, it will fail: ```text -running 1 test -test tests::greater_than_100 ... FAILED - -failures: - -failures: - tests::greater_than_100 - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-08-guess-with-bug/output.txt}} ``` We don’t get a very helpful message in this case, but when we look at the test @@ -720,39 +464,7 @@ different messages depending on whether the value is too small or too large. Filename: src/lib.rs ```rust -# fn main() {} -# pub struct Guess { -# value: i32, -# } -# -// --snip-- - -impl Guess { - pub fn new(value: i32) -> Guess { - if value < 1 { - panic!("Guess value must be greater than or equal to 1, got {}.", - value); - } else if value > 100 { - panic!("Guess value must be less than or equal to 100, got {}.", - value); - } - - Guess { - value - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - #[should_panic(expected = "Guess value must be less than or equal to 100")] - fn greater_than_100() { - Guess::new(200); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-09/src/lib.rs:here}} ``` Listing 11-9: Testing that a condition will cause a @@ -773,32 +485,13 @@ fails, let’s again introduce a bug into our code by swapping the bodies of the `if value < 1` and the `else if value > 100` blocks: ```rust,ignore,not_desired_behavior -if value < 1 { - panic!("Guess value must be less than or equal to 100, got {}.", value); -} else if value > 100 { - panic!("Guess value must be greater than or equal to 1, got {}.", value); -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/src/lib.rs:here}} ``` This time when we run the `should_panic` test, it will fail: ```text -running 1 test -test tests::greater_than_100 ... FAILED - -failures: - ----- tests::greater_than_100 stdout ---- -thread 'tests::greater_than_100' panicked at 'Guess value must be -greater than or equal to 1, got 200.', src/lib.rs:11:13 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -note: Panic did not include expected string 'Guess value must be less than or -equal to 100' - -failures: - tests::greater_than_100 - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-09-guess-with-panic-msg-bug/output.txt}} ``` The failure message indicates that this test did indeed panic as we expected, @@ -814,17 +507,7 @@ that use `Result`! Here’s the test from Listing 11-1, rewritten to use `Result` and return an `Err` instead of panicking: ```rust -#[cfg(test)] -mod tests { - #[test] - fn it_works() -> Result<(), String> { - if 2 + 2 == 4 { - Ok(()) - } else { - Err(String::from("two plus two does not equal four")) - } - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs}} ``` The `it_works` function now has a return type, `Result<(), String>`. In the diff --git a/src/doc/book/src/ch11-02-running-tests.md b/src/doc/book/src/ch11-02-running-tests.md index 26293d1902..2a83f57bbd 100644 --- a/src/doc/book/src/ch11-02-running-tests.md +++ b/src/doc/book/src/ch11-02-running-tests.md @@ -62,27 +62,7 @@ parameter and returns 10, as well as a test that passes and a test that fails. Filename: src/lib.rs ```rust,panics -fn prints_and_returns_10(a: i32) -> i32 { - println!("I got the value {}", a); - 10 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn this_test_will_pass() { - let value = prints_and_returns_10(4); - assert_eq!(10, value); - } - - #[test] - fn this_test_will_fail() { - let value = prints_and_returns_10(8); - assert_eq!(5, value); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-10/src/lib.rs}} ``` Listing 11-10: Tests for a function that calls @@ -91,23 +71,7 @@ mod tests { When we run these tests with `cargo test`, we’ll see the following output: ```text -running 2 tests -test tests::this_test_will_pass ... ok -test tests::this_test_will_fail ... FAILED - -failures: - ----- tests::this_test_will_fail stdout ---- -I got the value 8 -thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)` - left: `5`, - right: `10`', src/lib.rs:19:9 -note: Run with `RUST_BACKTRACE=1` for a backtrace. - -failures: - tests::this_test_will_fail - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-10/output.txt}} ``` Note that nowhere in this output do we see `I got the value 4`, which is what @@ -126,33 +90,7 @@ When we run the tests in Listing 11-10 again with the `--show-output` flag, we see the following output: ```text -running 2 tests -test tests::this_test_will_pass ... ok -test tests::this_test_will_fail ... FAILED - -successes: - ----- tests::this_test_will_pass stdout ---- -I got the value 4 - - -successes: - tests::this_test_will_pass - -failures: - ----- tests::this_test_will_fail stdout ---- -I got the value 8 -thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)` - left: `5`, - right: `10`', src/lib.rs:19:9 -note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. - - -failures: - tests::this_test_will_fail - -test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/output-only-01-show-output/output.txt}} ``` ### Running a Subset of Tests by Name @@ -168,29 +106,7 @@ To demonstrate how to run a subset of tests, we’ll create three tests for our Filename: src/lib.rs ```rust -pub fn add_two(a: i32) -> i32 { - a + 2 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn add_two_and_two() { - assert_eq!(4, add_two(2)); - } - - #[test] - fn add_three_and_two() { - assert_eq!(5, add_two(3)); - } - - #[test] - fn one_hundred() { - assert_eq!(102, add_two(100)); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-11/src/lib.rs}} ``` Listing 11-11: Three tests with three different @@ -200,12 +116,7 @@ If we run the tests without passing any arguments, as we saw earlier, all the tests will run in parallel: ```text -running 3 tests -test tests::add_two_and_two ... ok -test tests::add_three_and_two ... ok -test tests::one_hundred ... ok - -test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-11/output.txt}} ``` #### Running Single Tests @@ -213,14 +124,7 @@ test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out We can pass the name of any test function to `cargo test` to run only that test: ```text -$ cargo test one_hundred - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-06a75b4a1f2515e9 - -running 1 test -test tests::one_hundred ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out +{{#include ../listings/ch11-writing-automated-tests/output-only-02-single-test/output.txt}} ``` Only the test with the name `one_hundred` ran; the other two tests didn’t match @@ -237,15 +141,7 @@ will be run. For example, because two of our tests’ names contain `add`, we ca run those two by running `cargo test add`: ```text -$ cargo test add - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-06a75b4a1f2515e9 - -running 2 tests -test tests::add_two_and_two ... ok -test tests::add_three_and_two ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out +{{#include ../listings/ch11-writing-automated-tests/output-only-03-multiple-tests/output.txt}} ``` This command ran all tests with `add` in the name and filtered out the test @@ -264,46 +160,21 @@ here: Filename: src/lib.rs ```rust -#[test] -fn it_works() { - assert_eq!(2 + 2, 4); -} - -#[test] -#[ignore] -fn expensive_test() { - // code that takes an hour to run -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/src/lib.rs:here}} ``` After `#[test]` we add the `#[ignore]` line to the test we want to exclude. Now when we run our tests, `it_works` runs, but `expensive_test` doesn’t: ```text -$ cargo test - Compiling adder v0.1.0 (file:///projects/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.24 secs - Running target/debug/deps/adder-ce99bcc2479f4607 - -running 2 tests -test expensive_test ... ignored -test it_works ... ok - -test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-11-ignore-a-test/output.txt}} ``` The `expensive_test` function is listed as `ignored`. If we want to run only the ignored tests, we can use `cargo test -- --ignored`: ```text -$ cargo test -- --ignored - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/deps/adder-ce99bcc2479f4607 - -running 1 test -test expensive_test ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out +{{#include ../listings/ch11-writing-automated-tests/output-only-04-running-ignored/output.txt}} ``` By controlling which tests run, you can make sure your `cargo test` results diff --git a/src/doc/book/src/ch11-03-test-organization.md b/src/doc/book/src/ch11-03-test-organization.md index 2af6a0e0f5..9ac9497593 100644 --- a/src/doc/book/src/ch11-03-test-organization.md +++ b/src/doc/book/src/ch11-03-test-organization.md @@ -38,13 +38,7 @@ this chapter, Cargo generated this code for us: Filename: src/lib.rs ```rust -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - assert_eq!(2 + 2, 4); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-01/src/lib.rs:here}} ``` This code is the automatically generated test module. The attribute `cfg` @@ -67,25 +61,7 @@ Consider the code in Listing 11-12 with the private function `internal_adder`. Filename: src/lib.rs ```rust -# fn main() {} - -pub fn add_two(a: i32) -> i32 { - internal_adder(a, 2) -} - -fn internal_adder(a: i32, b: i32) -> i32 { - a + b -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn internal() { - assert_eq!(4, internal_adder(2, 2)); - } -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-12/src/lib.rs:here}} ``` Listing 11-12: Testing a private function @@ -120,12 +96,7 @@ Let’s create an integration test. With the code in Listing 11-12 still in the Filename: tests/integration_test.rs ```rust,ignore -use adder; - -#[test] -fn it_adds_two() { - assert_eq!(4, adder::add_two(2)); -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/listing-11-13/tests/integration_test.rs}} ``` Listing 11-13: An integration test of a function in the @@ -140,28 +111,7 @@ We don’t need to annotate any code in *tests/integration_test.rs* with in this directory only when we run `cargo test`. Run `cargo test` now: ```text -$ cargo test - Compiling adder v0.1.0 (file:///projects/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs - Running target/debug/deps/adder-abcabcabc - -running 1 test -test tests::internal ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/integration_test-ce99bcc2479f4607 - -running 1 test -test it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/listing-11-13/output.txt}} ``` The three sections of output include the unit tests, the integration test, and @@ -187,14 +137,7 @@ particular integration test file, use the `--test` argument of `cargo test` followed by the name of the file: ```text -$ cargo test --test integration_test - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running target/debug/integration_test-952a27e0126bb565 - -running 1 test -test it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/output-only-05-single-integration/output.txt}} ``` This command runs only the tests in the *tests/integration_test.rs* file. @@ -224,9 +167,7 @@ multiple test files: Filename: tests/common.rs ```rust -pub fn setup() { - // setup code specific to your library's tests would go here -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/tests/common.rs}} ``` When we run the tests again, we’ll see a new section in the test output for the @@ -234,29 +175,7 @@ When we run the tests again, we’ll see a new section in the test output for th did we call the `setup` function from anywhere: ```text -running 1 test -test tests::internal ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/common-b8b07b6f1be2db70 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Running target/debug/deps/integration_test-d993c68b431d39df - -running 1 test -test it_adds_two ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - - Doc-tests adder - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +{{#include ../listings/ch11-writing-automated-tests/no-listing-12-shared-test-code-problem/output.txt}} ``` Having `common` appear in the test results with `running 0 tests` displayed for @@ -279,15 +198,7 @@ function from the `it_adds_two` test in *tests/integration_test.rs*: Filename: tests/integration_test.rs ```rust,ignore -use adder; - -mod common; - -#[test] -fn it_adds_two() { - common::setup(); - assert_eq!(4, adder::add_two(2)); -} +{{#rustdoc_include ../listings/ch11-writing-automated-tests/no-listing-13-fix-shared-test-code-problem/tests/integration_test.rs}} ``` Note that the `mod common;` declaration is the same as the module declaration diff --git a/src/doc/book/src/ch12-01-accepting-command-line-arguments.md b/src/doc/book/src/ch12-01-accepting-command-line-arguments.md index 5f4f61e88c..f327361f61 100644 --- a/src/doc/book/src/ch12-01-accepting-command-line-arguments.md +++ b/src/doc/book/src/ch12-01-accepting-command-line-arguments.md @@ -41,12 +41,7 @@ command line arguments passed to it and then collect the values into a vector. Filename: src/main.rs ```rust -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - println!("{:?}", args); -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-01/src/main.rs}} ``` Listing 12-1: Collecting the command line arguments into @@ -83,13 +78,11 @@ Finally, we print the vector using the debug formatter, `:?`. Let’s try runnin the code first with no arguments and then with two arguments: ```text -$ cargo run ---snip-- -["target/debug/minigrep"] +{{#include ../listings/ch12-an-io-project/listing-12-01/output.txt}} +``` -$ cargo run needle haystack ---snip-- -["target/debug/minigrep", "needle", "haystack"] +```text +{{#include ../listings/ch12-an-io-project/output-only-01-with-args/output.txt}} ``` Notice that the first value in the vector is `"target/debug/minigrep"`, which @@ -110,17 +103,7 @@ throughout the rest of the program. We do that in Listing 12-2. Filename: src/main.rs ```rust,should_panic -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - - let query = &args[1]; - let filename = &args[2]; - - println!("Searching for {}", query); - println!("In file {}", filename); -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-02/src/main.rs}} ``` Listing 12-2: Creating variables to hold the query @@ -138,12 +121,7 @@ working as we intend. Let’s run this program again with the arguments `test` and `sample.txt`: ```text -$ cargo run test sample.txt - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep test sample.txt` -Searching for test -In file sample.txt +{{#include ../listings/ch12-an-io-project/listing-12-02/output.txt}} ``` Great, the program is working! The values of the arguments we need are being diff --git a/src/doc/book/src/ch12-02-reading-a-file.md b/src/doc/book/src/ch12-02-reading-a-file.md index 8c4c92ec8d..0b07e7a705 100644 --- a/src/doc/book/src/ch12-02-reading-a-file.md +++ b/src/doc/book/src/ch12-02-reading-a-file.md @@ -11,15 +11,7 @@ Who are you?” Filename: poem.txt ```text -I'm nobody! Who are you? -Are you nobody, too? -Then there's a pair of us - don't tell! -They'd banish us, you know. - -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! +{{#include ../listings/ch12-an-io-project/listing-12-03/poem.txt}} ``` Listing 12-3: A poem by Emily Dickinson makes a good test @@ -31,24 +23,7 @@ shown in Listing 12-4. Filename: src/main.rs ```rust,should_panic -use std::env; -use std::fs; - -fn main() { -# let args: Vec = env::args().collect(); -# -# let query = &args[1]; -# let filename = &args[2]; -# -# println!("Searching for {}", query); - // --snip-- - println!("In file {}", filename); - - let contents = fs::read_to_string(filename) - .expect("Something went wrong reading the file"); - - println!("With text:\n{}", contents); -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-04/src/main.rs:here}} ``` Listing 12-4: Reading the contents of the file specified @@ -70,22 +45,7 @@ we haven’t implemented the searching part yet) and the *poem.txt* file as the second argument: ```text -$ cargo run the poem.txt - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep the poem.txt` -Searching for the -In file poem.txt -With text: -I'm nobody! Who are you? -Are you nobody, too? -Then there's a pair of us — don't tell! -They'd banish us, you know. - -How dreary to be somebody! -How public, like a frog -To tell your name the livelong day -To an admiring bog! +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-04/output.txt}} ``` Great! The code read and then printed the contents of the file. But the code diff --git a/src/doc/book/src/ch12-03-improving-error-handling-and-modularity.md b/src/doc/book/src/ch12-03-improving-error-handling-and-modularity.md index d26c590049..cf5bd88e1f 100644 --- a/src/doc/book/src/ch12-03-improving-error-handling-and-modularity.md +++ b/src/doc/book/src/ch12-03-improving-error-handling-and-modularity.md @@ -75,20 +75,7 @@ function `parse_config`, which we’ll define in *src/main.rs* for the moment. Filename: src/main.rs ```rust,ignore -fn main() { - let args: Vec = env::args().collect(); - - let (query, filename) = parse_config(&args); - - // --snip-- -} - -fn parse_config(args: &[String]) -> (&str, &str) { - let query = &args[1]; - let filename = &args[2]; - - (query, filename) -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-05/src/main.rs:here}} ``` Listing 12-5: Extracting a `parse_config` function from @@ -133,34 +120,7 @@ Listing 12-6 shows the improvements to the `parse_config` function. Filename: src/main.rs ```rust,should_panic -# use std::env; -# use std::fs; -# -fn main() { - let args: Vec = env::args().collect(); - - let config = parse_config(&args); - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - let contents = fs::read_to_string(config.filename) - .expect("Something went wrong reading the file"); - - // --snip-- -} - -struct Config { - query: String, - filename: String, -} - -fn parse_config(args: &[String]) -> Config { - let query = args[1].clone(); - let filename = args[2].clone(); - - Config { query, filename } -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-06/src/main.rs:here}} ``` Listing 12-6: Refactoring `parse_config` to return an @@ -228,31 +188,7 @@ shows the changes we need to make. Filename: src/main.rs ```rust,should_panic -# use std::env; -# -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args); - - // --snip-- -} - -# struct Config { -# query: String, -# filename: String, -# } -# -// --snip-- - -impl Config { - fn new(args: &[String]) -> Config { - let query = args[1].clone(); - let filename = args[2].clone(); - - Config { query, filename } - } -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-07/src/main.rs:here}} ``` Listing 12-7: Changing `parse_config` into @@ -271,13 +207,7 @@ panic if the vector contains fewer than three items. Try running the program without any arguments; it will look like this: ```text -$ cargo run - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep` -thread 'main' panicked at 'index out of bounds: the len is 1 -but the index is 1', src/main.rs:25:21 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch12-an-io-project/listing-12-07/output.txt}} ``` The line `index out of bounds: the len is 1 but the index is 1` is an error @@ -294,12 +224,7 @@ out of bounds` message. Filename: src/main.rs ```rust,ignore -// --snip-- -fn new(args: &[String]) -> Config { - if args.len() < 3 { - panic!("not enough arguments"); - } - // --snip-- +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-08/src/main.rs:here}} ``` Listing 12-8: Adding a check for the number of @@ -317,12 +242,7 @@ With these extra few lines of code in `new`, let’s run the program without any arguments again to see what the error looks like now: ```text -$ cargo run - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs - Running `target/debug/minigrep` -thread 'main' panicked at 'not enough arguments', src/main.rs:26:13 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch12-an-io-project/listing-12-08/output.txt}} ``` This output is better: we now have a reasonable error message. However, we also @@ -350,18 +270,7 @@ next listing. Filename: src/main.rs ```rust,ignore -impl Config { - fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let query = args[1].clone(); - let filename = args[2].clone(); - - Ok(Config { query, filename }) - } -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-09/src/main.rs:here}} ``` Listing 12-9: Returning a `Result` from @@ -394,17 +303,7 @@ program that the program exited with an error state. Filename: src/main.rs ```rust,ignore -use std::process; - -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - println!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // --snip-- +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-10/src/main.rs:here}} ``` Listing 12-10: Exiting with an error code if creating a @@ -433,11 +332,7 @@ number that was passed as the exit status code. This is similar to the extra output. Let’s try it: ```text -$ cargo run - Compiling minigrep v0.1.0 (file:///projects/minigrep) - Finished dev [unoptimized + debuginfo] target(s) in 0.48 secs - Running `target/debug/minigrep` -Problem parsing arguments: not enough arguments +{{#include ../listings/ch12-an-io-project/listing-12-10/output.txt}} ``` Great! This output is much friendlier for our users. @@ -459,23 +354,7 @@ defining the function in *src/main.rs*. Filename: src/main.rs ```rust,ignore -fn main() { - // --snip-- - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - run(config); -} - -fn run(config: Config) { - let contents = fs::read_to_string(config.filename) - .expect("Something went wrong reading the file"); - - println!("With text:\n{}", contents); -} - -// --snip-- +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-11/src/main.rs:here}} ``` Listing 12-11: Extracting a `run` function containing the @@ -498,17 +377,7 @@ signature and body of `run`. Filename: src/main.rs ```rust,ignore -use std::error::Error; - -// --snip-- - -fn run(config: Config) -> Result<(), Box> { - let contents = fs::read_to_string(config.filename)?; - - println!("With text:\n{}", contents); - - Ok(()) -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-12/src/main.rs:here}} ``` Listing 12-12: Changing the `run` function to return @@ -543,14 +412,7 @@ it doesn’t return a value we need. When you run this code, it will compile but will display a warning: ```text -warning: unused `std::result::Result` that must be used - --> src/main.rs:17:5 - | -17 | run(config); - | ^^^^^^^^^^^^ - | - = note: #[warn(unused_must_use)] on by default - = note: this `Result` may be an `Err` variant, which should be handled +{{#include ../listings/ch12-an-io-project/listing-12-12/output.txt}} ``` Rust tells us that our code ignored the `Result` value and the `Result` value @@ -566,18 +428,7 @@ with `Config::new` in Listing 12-10, but with a slight difference: Filename: src/main.rs ```rust,ignore -fn main() { - // --snip-- - - println!("Searching for {}", config.query); - println!("In file {}", config.filename); - - if let Err(e) = run(config) { - println!("Application error: {}", e); - - process::exit(1); - } -} +{{#rustdoc_include ../listings/ch12-an-io-project/no-listing-01-handling-errors-in-main/src/main.rs:here}} ``` We use `if let` rather than `unwrap_or_else` to check whether `run` returns an @@ -611,23 +462,7 @@ compile until we modify *src/main.rs* in Listing 12-14. Filename: src/lib.rs ```rust,ignore -use std::error::Error; -use std::fs; - -pub struct Config { - pub query: String, - pub filename: String, -} - -impl Config { - pub fn new(args: &[String]) -> Result { - // --snip-- - } -} - -pub fn run(config: Config) -> Result<(), Box> { - // --snip-- -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-13/src/lib.rs:here}} ``` Listing 12-13: Moving `Config` and `run` into @@ -643,17 +478,7 @@ binary crate in *src/main.rs*, as shown in Listing 12-14. Filename: src/main.rs ```rust,ignore -use std::env; -use std::process; - -use minigrep::Config; - -fn main() { - // --snip-- - if let Err(e) = minigrep::run(config) { - // --snip-- - } -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-14/src/main.rs:here}} ``` Listing 12-14: Using the `minigrep` library crate in diff --git a/src/doc/book/src/ch12-04-testing-the-librarys-functionality.md b/src/doc/book/src/ch12-04-testing-the-librarys-functionality.md index e8ed858dec..17a0f97dae 100644 --- a/src/doc/book/src/ch12-04-testing-the-librarys-functionality.md +++ b/src/doc/book/src/ch12-04-testing-the-librarys-functionality.md @@ -40,29 +40,8 @@ yet. Filename: src/lib.rs -```rust -# pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { -# vec![] -# } -# -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn one_result() { - let query = "duct"; - let contents = "\ -Rust: -safe, fast, productive. -Pick three."; - - assert_eq!( - vec!["safe, fast, productive."], - search(query, contents) - ); - } -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-15/src/lib.rs:here}} ``` Listing 12-15: Creating a failing test for the `search` @@ -82,9 +61,7 @@ containing the line `"safe, fast, productive."` Filename: src/lib.rs ```rust -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - vec![] -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-16/src/lib.rs:here}} ``` Listing 12-16: Defining just enough of the `search` @@ -109,15 +86,7 @@ If we forget the lifetime annotations and try to compile this function, we’ll get this error: ```text -error[E0106]: missing lifetime specifier - --> src/lib.rs:5:51 - | -5 | pub fn search(query: &str, contents: &str) -> Vec<&str> { - | ^ expected lifetime -parameter - | - = help: this function's return type contains a borrowed value, but the - signature does not say whether it is borrowed from `query` or `contents` +{{#include ../listings/ch12-an-io-project/output-only-02-missing-lifetimes/output.txt}} ``` Rust can’t possibly know which of the two arguments we need, so we need to tell @@ -134,31 +103,7 @@ References with Lifetimes”][validating-references-with-lifetimes] + ```text $ CASE_INSENSITIVE=1 cargo run to poem.txt - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep to poem.txt` Are you nobody, too? How dreary to be somebody! diff --git a/src/doc/book/src/ch12-06-writing-to-stderr-instead-of-stdout.md b/src/doc/book/src/ch12-06-writing-to-stderr-instead-of-stdout.md index 0fc1aa28ed..ab10ab1f52 100644 --- a/src/doc/book/src/ch12-06-writing-to-stderr-instead-of-stdout.md +++ b/src/doc/book/src/ch12-06-writing-to-stderr-instead-of-stdout.md @@ -1,13 +1,13 @@ ## Writing Error Messages to Standard Error Instead of Standard Output At the moment, we’re writing all of our output to the terminal using the -`println!` function. Most terminals provide two kinds of output: *standard +`println!` macro. Most terminals provide two kinds of output: *standard output* (`stdout`) for general information and *standard error* (`stderr`) for error messages. This distinction enables users to choose to direct the successful output of a program to a file but still print error messages to the screen. -The `println!` function is only capable of printing to standard output, so we +The `println!` macro is only capable of printing to standard output, so we have to use something else to print to standard error. ### Checking Where Errors Are Written @@ -57,20 +57,7 @@ instead. Filename: src/main.rs ```rust,ignore -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - eprintln!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - if let Err(e) = minigrep::run(config) { - eprintln!("Application error: {}", e); - - process::exit(1); - } -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-24/src/main.rs:here}} ``` Listing 12-24: Writing error messages to standard error diff --git a/src/doc/book/src/ch13-01-closures.md b/src/doc/book/src/ch13-01-closures.md index 56f8ed4586..09485da126 100644 --- a/src/doc/book/src/ch13-01-closures.md +++ b/src/doc/book/src/ch13-01-closures.md @@ -30,14 +30,7 @@ we passed in. Filename: src/main.rs ```rust -use std::thread; -use std::time::Duration; - -fn simulated_expensive_calculation(intensity: u32) -> u32 { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - intensity -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-01/src/main.rs:here}} ``` Listing 13-1: A function to stand in for a hypothetical @@ -62,16 +55,7 @@ function we’ll use. Filename: src/main.rs ```rust -fn main() { - let simulated_user_specified_value = 10; - let simulated_random_number = 7; - - generate_workout( - simulated_user_specified_value, - simulated_random_number - ); -} -# fn generate_workout(intensity: u32, random_number: u32) {} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-02/src/main.rs:here}} ``` Listing 13-2: A `main` function with hardcoded values to @@ -92,36 +76,7 @@ changes in this example will be made to this function. Filename: src/main.rs ```rust -# use std::thread; -# use std::time::Duration; -# -# fn simulated_expensive_calculation(num: u32) -> u32 { -# println!("calculating slowly..."); -# thread::sleep(Duration::from_secs(2)); -# num -# } -# -fn generate_workout(intensity: u32, random_number: u32) { - if intensity < 25 { - println!( - "Today, do {} pushups!", - simulated_expensive_calculation(intensity) - ); - println!( - "Next, do {} situps!", - simulated_expensive_calculation(intensity) - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - simulated_expensive_calculation(intensity) - ); - } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-03/src/main.rs:here}} ``` Listing 13-3: The business logic that prints the workout @@ -163,39 +118,7 @@ function into a variable, as shown in Listing 13-4. Filename: src/main.rs ```rust -# use std::thread; -# use std::time::Duration; -# -# fn simulated_expensive_calculation(num: u32) -> u32 { -# println!("calculating slowly..."); -# thread::sleep(Duration::from_secs(2)); -# num -# } -# -fn generate_workout(intensity: u32, random_number: u32) { - let expensive_result = - simulated_expensive_calculation(intensity); - - if intensity < 25 { - println!( - "Today, do {} pushups!", - expensive_result - ); - println!( - "Next, do {} situps!", - expensive_result - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - expensive_result - ); - } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-04/src/main.rs:here}} ``` Listing 13-4: Extracting the calls to @@ -222,15 +145,7 @@ the closure we’re introducing here. Filename: src/main.rs ```rust -# use std::thread; -# use std::time::Duration; -# -let expensive_closure = |num| { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num -}; -# expensive_closure(5); +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-05/src/main.rs:here}} ``` Listing 13-5: Defining a closure and storing it in the @@ -265,36 +180,7 @@ want to use, as shown in Listing 13-6. Filename: src/main.rs ```rust -# use std::thread; -# use std::time::Duration; -# -fn generate_workout(intensity: u32, random_number: u32) { - let expensive_closure = |num| { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num - }; - - if intensity < 25 { - println!( - "Today, do {} pushups!", - expensive_closure(intensity) - ); - println!( - "Next, do {} situps!", - expensive_closure(intensity) - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - expensive_closure(intensity) - ); - } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-06/src/main.rs:here}} ``` Listing 13-6: Calling the `expensive_closure` we’ve @@ -339,14 +225,7 @@ would look like the definition shown in Listing 13-7. Filename: src/main.rs ```rust -# use std::thread; -# use std::time::Duration; -# -let expensive_closure = |num: u32| -> u32 { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num -}; +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-07/src/main.rs:here}} ``` Listing 13-7: Adding optional type annotations of the @@ -370,7 +249,9 @@ The first line shows a function definition, and the second line shows a fully annotated closure definition. The third line removes the type annotations from the closure definition, and the fourth line removes the brackets, which are optional because the closure body has only one expression. These are all valid -definitions that will produce the same behavior when they’re called. +definitions that will produce the same behavior when they’re called. Calling +the closures is required for `add_one_v3` and `add_one_v4` to be able to +compile because the types will be inferred from their usage. Closure definitions will have one concrete type inferred for each of their parameters and for their return value. For instance, Listing 13-8 shows the @@ -383,10 +264,7 @@ first time and a `u32` the second time, we’ll get an error. Filename: src/main.rs ```rust,ignore,does_not_compile -let example_closure = |x| x; - -let s = example_closure(String::from("hello")); -let n = example_closure(5); +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-08/src/main.rs:here}} ``` Listing 13-8: Attempting to call a closure whose types @@ -395,15 +273,7 @@ are inferred with two different types The compiler gives us this error: ```text -error[E0308]: mismatched types - --> src/main.rs - | - | let n = example_closure(5); - | ^ expected struct `std::string::String`, found - integer - | - = note: expected type `std::string::String` - found type `{integer}` +{{#include ../listings/ch13-functional-features/listing-13-08/output.txt}} ``` The first time we call `example_closure` with the `String` value, the compiler @@ -451,12 +321,7 @@ and an optional result value. Filename: src/main.rs ```rust -struct Cacher - where T: Fn(u32) -> u32 -{ - calculation: T, - value: Option, -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-09/src/main.rs:here}} ``` Listing 13-9: Defining a `Cacher` struct that holds a @@ -486,34 +351,7 @@ The logic around the `value` field we’ve just described is defined in Listing Filename: src/main.rs ```rust -# struct Cacher -# where T: Fn(u32) -> u32 -# { -# calculation: T, -# value: Option, -# } -# -impl Cacher - where T: Fn(u32) -> u32 -{ - fn new(calculation: T) -> Cacher { - Cacher { - calculation, - value: None, - } - } - - fn value(&mut self, arg: u32) -> u32 { - match self.value { - Some(v) => v, - None => { - let v = (self.calculation)(arg); - self.value = Some(v); - v - }, - } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-10/src/main.rs:here}} ``` Listing 13-10: The caching logic of `Cacher` @@ -544,65 +382,7 @@ Listing 13-11 shows how we can use this `Cacher` struct in the function Filename: src/main.rs ```rust -# use std::thread; -# use std::time::Duration; -# -# struct Cacher -# where T: Fn(u32) -> u32 -# { -# calculation: T, -# value: Option, -# } -# -# impl Cacher -# where T: Fn(u32) -> u32 -# { -# fn new(calculation: T) -> Cacher { -# Cacher { -# calculation, -# value: None, -# } -# } -# -# fn value(&mut self, arg: u32) -> u32 { -# match self.value { -# Some(v) => v, -# None => { -# let v = (self.calculation)(arg); -# self.value = Some(v); -# v -# }, -# } -# } -# } -# -fn generate_workout(intensity: u32, random_number: u32) { - let mut expensive_result = Cacher::new(|num| { - println!("calculating slowly..."); - thread::sleep(Duration::from_secs(2)); - num - }); - - if intensity < 25 { - println!( - "Today, do {} pushups!", - expensive_result.value(intensity) - ); - println!( - "Next, do {} situps!", - expensive_result.value(intensity) - ); - } else { - if random_number == 3 { - println!("Take a break today! Remember to stay hydrated!"); - } else { - println!( - "Today, run for {} minutes!", - expensive_result.value(intensity) - ); - } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-11/src/main.rs:here}} ``` Listing 13-11: Using `Cacher` in the `generate_workout` @@ -634,15 +414,7 @@ same value for the parameter `arg` to the `value` method. That is, this test of `Cacher` will fail: ```rust,ignore,panics -#[test] -fn call_with_different_values() { - let mut c = Cacher::new(|a| a); - - let v1 = c.value(1); - let v2 = c.value(2); - - assert_eq!(v2, 2); -} +{{#rustdoc_include ../listings/ch13-functional-features/no-listing-01-failing-cacher-test/src/lib.rs:here}} ``` This test creates a new `Cacher` instance with a closure that returns the value @@ -654,9 +426,7 @@ Run this test with the `Cacher` implementation in Listing 13-9 and Listing 13-10, and the test will fail on the `assert_eq!` with this message: ```text -thread 'call_with_different_values' panicked at 'assertion failed: `(left == right)` - left: `1`, - right: `2`', src/main.rs +{{#include ../listings/ch13-functional-features/no-listing-01-failing-cacher-test/output.txt}} ``` The problem is that the first time we called `c.value` with 1, the `Cacher` @@ -690,15 +460,7 @@ that uses the `x` variable from the closure’s surrounding environment. Filename: src/main.rs ```rust -fn main() { - let x = 4; - - let equal_to_x = |z| z == x; - - let y = 4; - - assert!(equal_to_x(y)); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-12/src/main.rs}} ``` Listing 13-12: Example of a closure that refers to a @@ -714,26 +476,13 @@ code won’t compile: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let x = 4; - - fn equal_to_x(z: i32) -> bool { z == x } - - let y = 4; - - assert!(equal_to_x(y)); -} +{{#rustdoc_include ../listings/ch13-functional-features/no-listing-02-functions-cant-capture/src/main.rs}} ``` We get an error: ```text -error[E0434]: can't capture dynamic environment in a fn item; use the || { ... -} closure form instead - --> src/main.rs - | -4 | fn equal_to_x(z: i32) -> bool { z == x } - | ^ +{{#include ../listings/ch13-functional-features/no-listing-02-functions-cant-capture/output.txt}} ``` The compiler even reminds us that this only works with closures! @@ -780,33 +529,13 @@ yet compile. Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let x = vec![1, 2, 3]; - - let equal_to_x = move |z| z == x; - - println!("can't use x here: {:?}", x); - - let y = vec![1, 2, 3]; - - assert!(equal_to_x(y)); -} +{{#rustdoc_include ../listings/ch13-functional-features/no-listing-03-move-closures/src/main.rs}} ``` We receive the following error: ```text -error[E0382]: use of moved value: `x` - --> src/main.rs:6:40 - | -4 | let equal_to_x = move |z| z == x; - | -------- value moved (into closure) here -5 | -6 | println!("can't use x here: {:?}", x); - | ^ value used here after move - | - = note: move occurs because `x` has type `std::vec::Vec`, which does not - implement the `Copy` trait +{{#include ../listings/ch13-functional-features/no-listing-03-move-closures/output.txt}} ``` The `x` value is moved into the closure when the closure is defined, because we diff --git a/src/doc/book/src/ch13-02-iterators.md b/src/doc/book/src/ch13-02-iterators.md index 493c3696c5..0b40e88417 100644 --- a/src/doc/book/src/ch13-02-iterators.md +++ b/src/doc/book/src/ch13-02-iterators.md @@ -12,9 +12,7 @@ the `iter` method defined on `Vec`. This code by itself doesn’t do anything useful. ```rust -let v1 = vec![1, 2, 3]; - -let v1_iter = v1.iter(); +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-13/src/main.rs:here}} ``` Listing 13-13: Creating an iterator @@ -30,13 +28,7 @@ called using the iterator in `v1_iter`, each element in the iterator is used in one iteration of the loop, which prints out each value. ```rust -let v1 = vec![1, 2, 3]; - -let v1_iter = v1.iter(); - -for val in v1_iter { - println!("Got: {}", val); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-14/src/main.rs:here}} ``` Listing 13-14: Using an iterator in a `for` loop @@ -86,17 +78,7 @@ from the vector. Filename: src/lib.rs ```rust -#[test] -fn iterator_demonstration() { - let v1 = vec![1, 2, 3]; - - let mut v1_iter = v1.iter(); - - assert_eq!(v1_iter.next(), Some(&1)); - assert_eq!(v1_iter.next(), Some(&2)); - assert_eq!(v1_iter.next(), Some(&3)); - assert_eq!(v1_iter.next(), None); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-15/src/lib.rs:here}} ``` Listing 13-15: Calling the `next` method on an @@ -135,16 +117,7 @@ test illustrating a use of the `sum` method: Filename: src/lib.rs ```rust -#[test] -fn iterator_sum() { - let v1 = vec![1, 2, 3]; - - let v1_iter = v1.iter(); - - let total: i32 = v1_iter.sum(); - - assert_eq!(total, 6); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-16/src/lib.rs:here}} ``` Listing 13-16: Calling the `sum` method to get the total @@ -169,9 +142,7 @@ incremented by 1. However, this code produces a warning: Filename: src/main.rs ```rust,not_desired_behavior -let v1: Vec = vec![1, 2, 3]; - -v1.iter().map(|x| x + 1); +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-17/src/main.rs:here}} ``` Listing 13-17: Calling the iterator adaptor `map` to @@ -180,14 +151,7 @@ create a new iterator The warning we get is this: ```text -warning: unused `std::iter::Map` which must be used: iterator adaptors are lazy -and do nothing unless consumed - --> src/main.rs:4:5 - | -4 | v1.iter().map(|x| x + 1); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: #[warn(unused_must_use)] on by default +{{#include ../listings/ch13-functional-features/listing-13-17/output.txt}} ``` The code in Listing 13-17 doesn’t do anything; the closure we’ve specified @@ -205,11 +169,7 @@ containing each item from the original vector incremented by 1. Filename: src/main.rs ```rust -let v1: Vec = vec![1, 2, 3]; - -let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); - -assert_eq!(v2, vec![2, 3, 4]); +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-18/src/main.rs:here}} ``` Listing 13-18: Calling the `map` method to create a new @@ -237,36 +197,7 @@ instances. It will return only shoes that are the specified size. Filename: src/lib.rs ```rust -#[derive(PartialEq, Debug)] -struct Shoe { - size: u32, - style: String, -} - -fn shoes_in_my_size(shoes: Vec, shoe_size: u32) -> Vec { - shoes.into_iter() - .filter(|s| s.size == shoe_size) - .collect() -} - -#[test] -fn filters_by_size() { - let shoes = vec![ - Shoe { size: 10, style: String::from("sneaker") }, - Shoe { size: 13, style: String::from("sandal") }, - Shoe { size: 10, style: String::from("boot") }, - ]; - - let in_my_size = shoes_in_my_size(shoes, 10); - - assert_eq!( - in_my_size, - vec![ - Shoe { size: 10, style: String::from("sneaker") }, - Shoe { size: 10, style: String::from("boot") }, - ] - ); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-19/src/lib.rs}} ``` Listing 13-19: Using the `filter` method with a closure @@ -311,15 +242,7 @@ Listing 13-20 has the definition of the `Counter` struct and an associated Filename: src/lib.rs ```rust -struct Counter { - count: u32, -} - -impl Counter { - fn new() -> Counter { - Counter { count: 0 } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-20/src/lib.rs}} ``` Listing 13-20: Defining the `Counter` struct and a `new` @@ -339,23 +262,7 @@ iterator is used, as shown in Listing 13-21: Filename: src/lib.rs ```rust -# struct Counter { -# count: u32, -# } -# -impl Iterator for Counter { - type Item = u32; - - fn next(&mut self) -> Option { - self.count += 1; - - if self.count < 6 { - Some(self.count) - } else { - None - } - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-21/src/lib.rs:here}} ``` Listing 13-21: Implementing the `Iterator` trait on our @@ -366,9 +273,10 @@ iterator will return `u32` values. Again, don’t worry about associated types yet, we’ll cover them in Chapter 19. We want our iterator to add 1 to the current state, so we initialized `count` -to 0 so it would return 1 first. If the value of `count` is less than 6, `next` -will return the current value wrapped in `Some`, but if `count` is 6 or higher, -our iterator will return `None`. +to 0 so it would return 1 first. If the value of `count` is less than 5, `next` +will increment `count` and return the current value wrapped in `Some`. Once +`count` is 5, our iterator will stop incrementing `count` and always return +`None`. #### Using Our `Counter` Iterator’s `next` Method @@ -380,35 +288,7 @@ with the iterator created from a vector in Listing 13-15. Filename: src/lib.rs ```rust -# struct Counter { -# count: u32, -# } -# -# impl Iterator for Counter { -# type Item = u32; -# -# fn next(&mut self) -> Option { -# self.count += 1; -# -# if self.count < 6 { -# Some(self.count) -# } else { -# None -# } -# } -# } -# -#[test] -fn calling_next_directly() { - let mut counter = Counter::new(); - - assert_eq!(counter.next(), Some(1)); - assert_eq!(counter.next(), Some(2)); - assert_eq!(counter.next(), Some(3)); - assert_eq!(counter.next(), Some(4)); - assert_eq!(counter.next(), Some(5)); - assert_eq!(counter.next(), None); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-22/src/lib.rs:here}} ``` Listing 13-22: Testing the functionality of the `next` @@ -433,41 +313,7 @@ together, we could do so, as shown in the test in Listing 13-23: Filename: src/lib.rs ```rust -# struct Counter { -# count: u32, -# } -# -# impl Counter { -# fn new() -> Counter { -# Counter { count: 0 } -# } -# } -# -# impl Iterator for Counter { -# // Our iterator will produce u32s -# type Item = u32; -# -# fn next(&mut self) -> Option { -# // increment our count. This is why we started at zero. -# self.count += 1; -# -# // check to see if we've finished counting or not. -# if self.count < 6 { -# Some(self.count) -# } else { -# None -# } -# } -# } -# -#[test] -fn using_other_iterator_trait_methods() { - let sum: u32 = Counter::new().zip(Counter::new().skip(1)) - .map(|(a, b)| a * b) - .filter(|x| x % 3 == 0) - .sum(); - assert_eq!(18, sum); -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-23/src/lib.rs:here}} ``` Listing 13-23: Using a variety of `Iterator` trait diff --git a/src/doc/book/src/ch13-03-improving-our-io-project.md b/src/doc/book/src/ch13-03-improving-our-io-project.md index e6ee68dc50..0473b2cba8 100644 --- a/src/doc/book/src/ch13-03-improving-our-io-project.md +++ b/src/doc/book/src/ch13-03-improving-our-io-project.md @@ -5,7 +5,6 @@ Chapter 12 by using iterators to make places in the code clearer and more concise. Let’s look at how iterators can improve our implementation of the `Config::new` function and the `search` function. - ### Removing a `clone` Using an Iterator In Listing 12-6, we added code that took a slice of `String` values and created @@ -17,20 +16,7 @@ Listing 12-23: Filename: src/lib.rs ```rust,ignore -impl Config { - pub fn new(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } - - let query = args[1].clone(); - let filename = args[2].clone(); - - let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - Ok(Config { query, filename, case_sensitive }) - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-12-23-reproduced/src/lib.rs:ch13}} ``` Listing 13-24: Reproduction of the `Config::new` function @@ -61,16 +47,7 @@ Open your I/O project’s *src/main.rs* file, which should look like this: Filename: src/main.rs ```rust,ignore -fn main() { - let args: Vec = env::args().collect(); - - let config = Config::new(&args).unwrap_or_else(|err| { - eprintln!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // --snip-- -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-12-24-reproduced/src/main.rs:ch13}} ``` We’ll change the start of the `main` function that we had in Listing 12-24 to @@ -80,14 +57,7 @@ well. Filename: src/main.rs ```rust,ignore -fn main() { - let config = Config::new(env::args()).unwrap_or_else(|err| { - eprintln!("Problem parsing arguments: {}", err); - process::exit(1); - }); - - // --snip-- -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-25/src/main.rs:here}} ``` Listing 13-25: Passing the return value of `env::args` to @@ -106,9 +76,7 @@ body. Filename: src/lib.rs ```rust,ignore -impl Config { - pub fn new(mut args: std::env::Args) -> Result { - // --snip-- +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-26/src/lib.rs:here}} ``` Listing 13-26: Updating the signature of `Config::new` to @@ -131,34 +99,7 @@ Listing 12-23 to use the `next` method: Filename: src/lib.rs ```rust -# fn main() {} -# use std::env; -# -# struct Config { -# query: String, -# filename: String, -# case_sensitive: bool, -# } -# -impl Config { - pub fn new(mut args: std::env::Args) -> Result { - args.next(); - - let query = match args.next() { - Some(arg) => arg, - None => return Err("Didn't get a query string"), - }; - - let filename = match args.next() { - Some(arg) => arg, - None => return Err("Didn't get a file name"), - }; - - let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - Ok(Config { query, filename, case_sensitive }) - } -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-27/src/lib.rs:here}} ``` Listing 13-27: Changing the body of `Config::new` to use @@ -180,17 +121,7 @@ project, which is reproduced here in Listing 13-28 as it was in Listing 12-19: Filename: src/lib.rs ```rust,ignore -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(query) { - results.push(line); - } - } - - results -} +{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-19/src/lib.rs:ch13}} ``` Listing 13-28: The implementation of the `search` @@ -206,11 +137,7 @@ concurrent access to the `results` vector. Listing 13-29 shows this change: Filename: src/lib.rs ```rust,ignore -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - contents.lines() - .filter(|line| line.contains(query)) - .collect() -} +{{#rustdoc_include ../listings/ch13-functional-features/listing-13-29/src/lib.rs:here}} ``` Listing 13-29: Using iterator adaptor methods in the diff --git a/src/doc/book/src/ch14-01-release-profiles.md b/src/doc/book/src/ch14-01-release-profiles.md index ab2400511e..24a36aefef 100644 --- a/src/doc/book/src/ch14-01-release-profiles.md +++ b/src/doc/book/src/ch14-01-release-profiles.md @@ -12,11 +12,18 @@ and the `release` profile has good defaults for release builds. These profile names might be familiar from the output of your builds: + + ```text $ cargo build - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.0s $ cargo build --release - Finished release [optimized] target(s) in 0.0 secs + Finished release [optimized] target(s) in 0.0s ``` The `dev` and `release` shown in this build output indicate that the compiler diff --git a/src/doc/book/src/ch14-02-publishing-to-crates-io.md b/src/doc/book/src/ch14-02-publishing-to-crates-io.md index f1b10f7c95..4e5c22067c 100644 --- a/src/doc/book/src/ch14-02-publishing-to-crates-io.md +++ b/src/doc/book/src/ch14-02-publishing-to-crates-io.md @@ -29,19 +29,7 @@ for an `add_one` function in a crate named `my_crate`: Filename: src/lib.rs ```rust,ignore -/// Adds one to the number given. -/// -/// # Examples -/// -/// ``` -/// let arg = 5; -/// let answer = my_crate::add_one(arg); -/// -/// assert_eq!(6, answer); -/// ``` -pub fn add_one(x: i32) -> i32 { - x + 1 -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-01/src/lib.rs}} ``` Listing 14-1: A documentation comment for a @@ -96,6 +84,12 @@ that don’t work because the code has changed since the documentation was written. If we run `cargo test` with the documentation for the `add_one` function from Listing 14-1, we will see a section in the test results like this: + + ```text Doc-tests my_crate @@ -125,13 +119,7 @@ shown in Listing 14-2: Filename: src/lib.rs ```rust,ignore -//! # My Crate -//! -//! `my_crate` is a collection of utilities to make performing certain -//! calculations more convenient. - -/// Adds one to the number given. -// --snip-- +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-02/src/lib.rs:here}} ``` Listing 14-2: Documentation for the `my_crate` crate as a @@ -189,37 +177,7 @@ function named `mix`, as shown in Listing 14-3: Filename: src/lib.rs ```rust -//! # Art -//! -//! A library for modeling artistic concepts. - -pub mod kinds { - /// The primary colors according to the RYB color model. - pub enum PrimaryColor { - Red, - Yellow, - Blue, - } - - /// The secondary colors according to the RYB color model. - pub enum SecondaryColor { - Orange, - Green, - Purple, - } -} - -pub mod utils { - use crate::kinds::*; - - /// Combines two primary colors in equal amounts to create - /// a secondary color. - pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { - // --snip-- -# SecondaryColor::Orange - } -} -# fn main() {} +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-03/src/lib.rs:here}} ``` Listing 14-3: An `art` library with items organized into @@ -245,14 +203,7 @@ currently defined. Listing 14-4 shows an example of a crate that uses the Filename: src/main.rs ```rust,ignore -use art::kinds::PrimaryColor; -use art::utils::mix; - -fn main() { - let red = PrimaryColor::Red; - let yellow = PrimaryColor::Yellow; - mix(red, yellow); -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-04/src/main.rs}} ``` Listing 14-4: A crate using the `art` crate’s items with @@ -276,21 +227,7 @@ items at the top level, as shown in Listing 14-5: Filename: src/lib.rs ```rust,ignore -//! # Art -//! -//! A library for modeling artistic concepts. - -pub use self::kinds::PrimaryColor; -pub use self::kinds::SecondaryColor; -pub use self::utils::mix; - -pub mod kinds { - // --snip-- -} - -pub mod utils { - // --snip-- -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-05/src/lib.rs:here}} ``` Listing 14-5: Adding `pub use` statements to re-export @@ -312,12 +249,7 @@ structure in Listing 14-5, as shown in Listing 14-6: Filename: src/main.rs ```rust,ignore -use art::PrimaryColor; -use art::mix; - -fn main() { - // --snip-- -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-06/src/main.rs:here}} ``` Listing 14-6: A program using the re-exported items from @@ -380,13 +312,19 @@ name = "guessing_game" Even if you’ve chosen a unique name, when you run `cargo publish` to publish the crate at this point, you’ll get a warning and then an error: + + ```text $ cargo publish - Updating registry `https://github.com/rust-lang/crates.io-index` -warning: manifest has no description, license, license-file, documentation, -homepage or repository. + Updating crates.io index +warning: manifest has no description, license, license-file, documentation, homepage or repository. +See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info. --snip-- -error: api errors: missing or empty metadata fields: description, license. +error: api errors (status 200 OK): missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for how to upload metadata ``` The reason is that you’re missing some crucial information: a description and @@ -461,15 +399,21 @@ no limit to the number of crate versions you can publish. Run the `cargo publish` command again. It should succeed now: + + ```text $ cargo publish - Updating registry `https://github.com/rust-lang/crates.io-index` -Packaging guessing_game v0.1.0 (file:///projects/guessing_game) -Verifying guessing_game v0.1.0 (file:///projects/guessing_game) -Compiling guessing_game v0.1.0 + Updating crates.io index + Packaging guessing_game v0.1.0 (file:///projects/guessing_game) + Verifying guessing_game v0.1.0 (file:///projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game/target/package/guessing_game-0.1.0) - Finished dev [unoptimized + debuginfo] target(s) in 0.19 secs -Uploading guessing_game v0.1.0 (file:///projects/guessing_game) + Finished dev [unoptimized + debuginfo] target(s) in 0.19s + Uploading guessing_game v0.1.0 (file:///projects/guessing_game) ``` Congratulations! You’ve now shared your code with the Rust community, and diff --git a/src/doc/book/src/ch14-03-cargo-workspaces.md b/src/doc/book/src/ch14-03-cargo-workspaces.md index a662ac219e..6054c734c0 100644 --- a/src/doc/book/src/ch14-03-cargo-workspaces.md +++ b/src/doc/book/src/ch14-03-cargo-workspaces.md @@ -33,19 +33,22 @@ by specifying the path to our binary crate; in this case, that path is *adder*: Filename: Cargo.toml ```toml -[workspace] - -members = [ - "adder", -] +{{#include ../listings/ch14-more-about-cargo/no-listing-01-workspace-with-adder-crate/add/Cargo.toml}} ``` Next, we’ll create the `adder` binary crate by running `cargo new` within the *add* directory: + + ```text $ cargo new adder - Created binary (application) `adder` project + Created binary (application) `adder` package ``` At this point, we can build the workspace by running `cargo build`. The files @@ -81,19 +84,21 @@ Change the top-level *Cargo.toml* to specify the *add-one* path in the Filename: Cargo.toml ```toml -[workspace] - -members = [ - "adder", - "add-one", -] +{{#include ../listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/Cargo.toml}} ``` Then generate a new library crate named `add-one`: + + ```text $ cargo new add-one --lib - Created library `add-one` project + Created library `add-one` package ``` Your *add* directory should now have these directories and files: @@ -117,9 +122,7 @@ In the *add-one/src/lib.rs* file, let’s add an `add_one` function: Filename: add-one/src/lib.rs ```rust -pub fn add_one(x: i32) -> i32 { - x + 1 -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/add-one/src/lib.rs}} ``` Now that we have a library crate in the workspace, we can have the binary crate @@ -129,9 +132,7 @@ dependency on `add-one` to *adder/Cargo.toml*. Filename: adder/Cargo.toml ```toml -[dependencies] - -add-one = { path = "../add-one" } +{{#include ../listings/ch14-more-about-cargo/no-listing-02-workspace-with-two-crates/add/adder/Cargo.toml:7:9}} ``` Cargo doesn’t assume that crates in a workspace will depend on each other, so @@ -145,12 +146,7 @@ function to call the `add_one` function, as in Listing 14-7. Filename: adder/src/main.rs ```rust,ignore -use add_one; - -fn main() { - let num = 10; - println!("Hello, world! {} plus one is {}!", num, add_one::add_one(num)); -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/listing-14-07/add/adder/src/main.rs}} ``` Listing 14-7: Using the `add-one` library crate from the @@ -159,20 +155,32 @@ fn main() { Let’s build the workspace by running `cargo build` in the top-level *add* directory! + + ```text $ cargo build Compiling add-one v0.1.0 (file:///projects/add/add-one) Compiling adder v0.1.0 (file:///projects/add/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.68 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.68s ``` To run the binary crate from the *add* directory, we need to specify which package in the workspace we want to use by using the `-p` argument and the package name with `cargo run`: + + ```text $ cargo run -p adder - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/adder` Hello, world! 10 plus one is 11! ``` @@ -201,23 +209,28 @@ crate: Filename: add-one/Cargo.toml ```toml -[dependencies] -rand = "0.5.5" +{{#include ../listings/ch14-more-about-cargo/no-listing-03-workspace-with-external-dependency/add/add-one/Cargo.toml:7:8}} ``` We can now add `use rand;` to the *add-one/src/lib.rs* file, and building the whole workspace by running `cargo build` in the *add* directory will bring in and compile the `rand` crate: + + ```text $ cargo build Updating crates.io index Downloaded rand v0.5.5 --snip-- - Compiling rand v0.5.5 + Compiling rand v0.5.6 Compiling add-one v0.1.0 (file:///projects/add/add-one) Compiling adder v0.1.0 (file:///projects/add/adder) - Finished dev [unoptimized + debuginfo] target(s) in 10.18 secs + Finished dev [unoptimized + debuginfo] target(s) in 10.18s ``` The top-level *Cargo.lock* now contains information about the dependency of @@ -226,14 +239,21 @@ workspace, we can’t use it in other crates in the workspace unless we add `rand` to their *Cargo.toml* files as well. For example, if we add `use rand;` to the *adder/src/main.rs* file for the `adder` crate, we’ll get an error: + + ```text $ cargo build + --snip-- Compiling adder v0.1.0 (file:///projects/add/adder) -error: use of unstable library feature 'rand': use `rand` from crates.io (see -issue #27703) - --> adder/src/main.rs:1:1 +error[E0432]: unresolved import `rand` + --> adder/src/main.rs:2:5 | -1 | use rand; +2 | use rand; + | ^^^^ no `rand` external crate ``` To fix this, edit the *Cargo.toml* file for the `adder` crate and indicate that @@ -253,28 +273,22 @@ within the `add_one` crate: Filename: add-one/src/lib.rs ```rust -pub fn add_one(x: i32) -> i32 { - x + 1 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - assert_eq!(3, add_one(2)); - } -} +{{#rustdoc_include ../listings/ch14-more-about-cargo/no-listing-04-workspace-with-tests/add/add-one/src/lib.rs}} ``` Now run `cargo test` in the top-level *add* directory: + + ```text $ cargo test Compiling add-one v0.1.0 (file:///projects/add/add-one) Compiling adder v0.1.0 (file:///projects/add/adder) - Finished dev [unoptimized + debuginfo] target(s) in 0.27 secs + Finished test [unoptimized + debuginfo] target(s) in 0.27s Running target/debug/deps/add_one-f0253159197f7841 running 1 test @@ -282,7 +296,7 @@ test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out - Running target/debug/deps/adder-f88af9d2cc175a5e + Running target/debug/deps/adder-49979ff40686fa8e running 0 tests @@ -305,9 +319,15 @@ We can also run tests for one particular crate in a workspace from the top-level directory by using the `-p` flag and specifying the name of the crate we want to test: + + ```text $ cargo test -p add-one - Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs + Finished test [unoptimized + debuginfo] target(s) in 0.00s Running target/debug/deps/add_one-b3235fea9a156f74 running 1 test diff --git a/src/doc/book/src/ch14-04-installing-binaries.md b/src/doc/book/src/ch14-04-installing-binaries.md index a654a371ac..6b2f58ba8c 100644 --- a/src/doc/book/src/ch14-04-installing-binaries.md +++ b/src/doc/book/src/ch14-04-installing-binaries.md @@ -21,17 +21,24 @@ For example, in Chapter 12 we mentioned that there’s a Rust implementation of the `grep` tool called `ripgrep` for searching files. If we want to install `ripgrep`, we can run the following: + + ```text $ cargo install ripgrep -Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading ripgrep v0.3.2 - --snip-- - Compiling ripgrep v0.3.2 - Finished release [optimized + debuginfo] target(s) in 97.91 secs + Updating crates.io index + Downloaded ripgrep v11.0.2 + Downloaded 1 crate (243.3 KB) in 0.88s + Installing ripgrep v11.0.2 +--snip-- + Compiling ripgrep v11.0.2 + Finished release [optimized] target(s) in 3m 10s Installing ~/.cargo/bin/rg + Installed package `ripgrep v11.0.2` (executable `rg`) ``` -The last line of the output shows the location and the name of the installed -binary, which in the case of `ripgrep` is `rg`. As long as the installation -directory is in your `$PATH`, as mentioned previously, you can then run `rg ---help` and start using a faster, rustier tool for searching files! +The second-to-last line of the output shows the location and the name of the +installed binary, which in the case of `ripgrep` is `rg`. As long as the +installation directory is in your `$PATH`, as mentioned previously, you can +then run `rg --help` and start using a faster, rustier tool for searching files! diff --git a/src/doc/book/src/ch15-01-box.md b/src/doc/book/src/ch15-01-box.md index 2b9a51b306..1605928d9a 100644 --- a/src/doc/book/src/ch15-01-box.md +++ b/src/doc/book/src/ch15-01-box.md @@ -38,10 +38,7 @@ Listing 15-1 shows how to use a box to store an `i32` value on the heap: Filename: src/main.rs ```rust -fn main() { - let b = Box::new(5); - println!("b = {}", b); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-01/src/main.rs}} ``` Listing 15-1: Storing an `i32` value on the heap using a @@ -109,10 +106,7 @@ we’ll demonstrate. Filename: src/main.rs ```rust,ignore,does_not_compile -enum List { - Cons(i32, List), - Nil, -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-02/src/main.rs:here}} ``` Listing 15-2: The first attempt at defining an enum to @@ -129,11 +123,7 @@ Listing 15-3: Filename: src/main.rs ```rust,ignore,does_not_compile -use crate::List::{Cons, Nil}; - -fn main() { - let list = Cons(1, Cons(2, Cons(3, Nil))); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-03/src/main.rs:here}} ``` Listing 15-3: Using the `List` enum to store the list `1, @@ -148,16 +138,7 @@ If we try to compile the code in Listing 15-3, we get the error shown in Listing 15-4: ```text -error[E0072]: recursive type `List` has infinite size - --> src/main.rs:1:1 - | -1 | enum List { - | ^^^^^^^^^ recursive type has infinite size -2 | Cons(i32, List), - | ----- recursive without indirection - | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `List` representable +{{#include ../listings/ch15-smart-pointers/listing-15-03/output.txt}} ``` Listing 15-4: The error we get when attempting to define @@ -176,12 +157,7 @@ Recall the `Message` enum we defined in Listing 6-2 when we discussed enum definitions in Chapter 6: ```rust -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(i32, i32, i32), -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs:here}} ``` To determine how much space to allocate for a `Message` value, Rust goes @@ -211,9 +187,12 @@ Rust can’t figure out how much space to allocate for recursively defined types so the compiler gives the error in Listing 15-4. But the error does include this helpful suggestion: + + ```text - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `List` representable + = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable ``` In this suggestion, “indirection” means that instead of storing a value @@ -235,19 +214,7 @@ of the `List` in Listing 15-3 to the code in Listing 15-5, which will compile: Filename: src/main.rs ```rust -enum List { - Cons(i32, Box), - Nil, -} - -use crate::List::{Cons, Nil}; - -fn main() { - let list = Cons(1, - Box::new(Cons(2, - Box::new(Cons(3, - Box::new(Nil)))))); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-05/src/main.rs}} ``` Listing 15-5: Definition of `List` that uses `Box` in diff --git a/src/doc/book/src/ch15-02-deref.md b/src/doc/book/src/ch15-02-deref.md index e0fae5b1a9..b2f608169a 100644 --- a/src/doc/book/src/ch15-02-deref.md +++ b/src/doc/book/src/ch15-02-deref.md @@ -29,13 +29,7 @@ reference to the data: Filename: src/main.rs ```rust -fn main() { - let x = 5; - let y = &x; - - assert_eq!(5, x); - assert_eq!(5, *y); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-06/src/main.rs}} ``` Listing 15-6: Using the dereference operator to follow a @@ -52,14 +46,7 @@ If we tried to write `assert_eq!(5, y);` instead, we would get this compilation error: ```text -error[E0277]: can't compare `{integer}` with `&{integer}` - --> src/main.rs:6:5 - | -6 | assert_eq!(5, y); - | ^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}` - | - = help: the trait `std::cmp::PartialEq<&{integer}>` is not implemented for - `{integer}` +{{#include ../listings/ch15-smart-pointers/output-only-01-comparing-to-reference/output.txt}} ``` Comparing a number and a reference to a number isn’t allowed because they’re @@ -74,13 +61,7 @@ reference; the dereference operator will work as shown in Listing 15-7: Filename: src/main.rs ```rust -fn main() { - let x = 5; - let y = Box::new(x); - - assert_eq!(5, x); - assert_eq!(5, *y); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-07/src/main.rs}} ``` Listing 15-7: Using the dereference operator on a @@ -107,13 +88,7 @@ Listing 15-8 defines a `MyBox` type in the same way. We’ll also define a Filename: src/main.rs ```rust -struct MyBox(T); - -impl MyBox { - fn new(x: T) -> MyBox { - MyBox(x) - } -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-08/src/main.rs:here}} ``` Listing 15-8: Defining a `MyBox` type @@ -131,13 +106,7 @@ code in Listing 15-9 won’t compile because Rust doesn’t know how to derefere Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let x = 5; - let y = MyBox::new(x); - - assert_eq!(5, x); - assert_eq!(5, *y); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-09/src/main.rs:here}} ``` Listing 15-9: Attempting to use `MyBox` in the same @@ -146,11 +115,7 @@ way we used references and `Box` Here’s the resulting compilation error: ```text -error[E0614]: type `MyBox<{integer}>` cannot be dereferenced - --> src/main.rs:14:19 - | -14 | assert_eq!(5, *y); - | ^^ +{{#include ../listings/ch15-smart-pointers/listing-15-09/output.txt}} ``` Our `MyBox` type can’t be dereferenced because we haven’t implemented that @@ -168,16 +133,7 @@ contains an implementation of `Deref` to add to the definition of `MyBox`: Filename: src/main.rs ```rust -use std::ops::Deref; - -# struct MyBox(T); -impl Deref for MyBox { - type Target = T; - - fn deref(&self) -> &T { - &self.0 - } -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-10/src/main.rs:here}} ``` Listing 15-10: Implementing `Deref` on `MyBox` @@ -226,13 +182,14 @@ Listing 15-9. ### Implicit Deref Coercions with Functions and Methods *Deref coercion* is a convenience that Rust performs on arguments to functions -and methods. Deref coercion converts a reference to a type that implements -`Deref` into a reference to a type that `Deref` can convert the original type -into. Deref coercion happens automatically when we pass a reference to a -particular type’s value as an argument to a function or method that doesn’t -match the parameter type in the function or method definition. A sequence of -calls to the `deref` method converts the type we provided into the type the -parameter needs. +and methods. Deref coercion works only on types that implement the `Deref` +trait. Deref coercion converts such a type into a reference to another type. +For example, deref coercion can convert `&String` to `&str` because `String` +implements the `Deref` trait such that it returns `str`. Deref coercion happens +automatically when we pass a reference to a particular type’s value as an +argument to a function or method that doesn’t match the parameter type in the +function or method definition. A sequence of calls to the `deref` method +converts the type we provided into the type the parameter needs. Deref coercion was added to Rust so that programmers writing function and method calls don’t need to add as many explicit references and dereferences @@ -247,9 +204,7 @@ parameter: Filename: src/main.rs ```rust -fn hello(name: &str) { - println!("Hello, {}!", name); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-11/src/main.rs:here}} ``` Listing 15-11: A `hello` function that has the parameter @@ -262,32 +217,7 @@ with a reference to a value of type `MyBox`, as shown in Listing 15-12: Filename: src/main.rs ```rust -# use std::ops::Deref; -# -# struct MyBox(T); -# -# impl MyBox { -# fn new(x: T) -> MyBox { -# MyBox(x) -# } -# } -# -# impl Deref for MyBox { -# type Target = T; -# -# fn deref(&self) -> &T { -# &self.0 -# } -# } -# -# fn hello(name: &str) { -# println!("Hello, {}!", name); -# } -# -fn main() { - let m = MyBox::new(String::from("Rust")); - hello(&m); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-12/src/main.rs:here}} ``` Listing 15-12: Calling `hello` with a reference to a @@ -308,32 +238,7 @@ of type `&MyBox`. Filename: src/main.rs ```rust -# use std::ops::Deref; -# -# struct MyBox(T); -# -# impl MyBox { -# fn new(x: T) -> MyBox { -# MyBox(x) -# } -# } -# -# impl Deref for MyBox { -# type Target = T; -# -# fn deref(&self) -> &T { -# &self.0 -# } -# } -# -# fn hello(name: &str) { -# println!("Hello, {}!", name); -# } -# -fn main() { - let m = MyBox::new(String::from("Rust")); - hello(&(*m)[..]); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-13/src/main.rs:here}} ``` Listing 15-13: The code we would have to write if Rust @@ -375,7 +280,8 @@ never coerce to mutable references. Because of the borrowing rules, if you have a mutable reference, that mutable reference must be the only reference to that data (otherwise, the program wouldn’t compile). Converting one mutable reference to one immutable reference will never break the borrowing rules. -Converting an immutable reference to a mutable reference would require that -there is only one immutable reference to that data, and the borrowing rules -don’t guarantee that. Therefore, Rust can’t make the assumption that converting -an immutable reference to a mutable reference is possible. +Converting an immutable reference to a mutable reference would require that the +initial immutable reference is the only immutable reference to that data, but +the borrowing rules don’t guarantee that. Therefore, Rust can’t make the +assumption that converting an immutable reference to a mutable reference is +possible. diff --git a/src/doc/book/src/ch15-03-drop.md b/src/doc/book/src/ch15-03-drop.md index 333e4e2c1d..8566f03061 100644 --- a/src/doc/book/src/ch15-03-drop.md +++ b/src/doc/book/src/ch15-03-drop.md @@ -30,21 +30,7 @@ function. Filename: src/main.rs ```rust -struct CustomSmartPointer { - data: String, -} - -impl Drop for CustomSmartPointer { - fn drop(&mut self) { - println!("Dropping CustomSmartPointer with data `{}`!", self.data); - } -} - -fn main() { - let c = CustomSmartPointer { data: String::from("my stuff") }; - let d = CustomSmartPointer { data: String::from("other stuff") }; - println!("CustomSmartPointers created."); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-14/src/main.rs}} ``` Listing 15-14: A `CustomSmartPointer` struct that @@ -66,9 +52,7 @@ call the `drop` method explicitly. When we run this program, we’ll see the following output: ```text -CustomSmartPointers created. -Dropping CustomSmartPointer with data `other stuff`! -Dropping CustomSmartPointer with data `my stuff`! +{{#include ../listings/ch15-smart-pointers/listing-15-14/output.txt}} ``` Rust automatically called `drop` for us when our instances went out of scope, @@ -96,12 +80,7 @@ compiler error: Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let c = CustomSmartPointer { data: String::from("some data") }; - println!("CustomSmartPointer created."); - c.drop(); - println!("CustomSmartPointer dropped before the end of main."); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-15/src/main.rs:here}} ``` Listing 15-15: Attempting to call the `drop` method from @@ -110,11 +89,7 @@ the `Drop` trait manually to clean up early When we try to compile this code, we’ll get this error: ```text -error[E0040]: explicit use of destructor method - --> src/main.rs:14:7 - | -14 | c.drop(); - | ^^^^ explicit destructor calls not allowed +{{#include ../listings/ch15-smart-pointers/listing-15-15/output.txt}} ``` This error message states that we’re not allowed to explicitly call `drop`. The @@ -140,22 +115,7 @@ an argument. The function is in the prelude, so we can modify `main` in Listing Filename: src/main.rs ```rust -# struct CustomSmartPointer { -# data: String, -# } -# -# impl Drop for CustomSmartPointer { -# fn drop(&mut self) { -# println!("Dropping CustomSmartPointer with data `{}`!", self.data); -# } -# } -# -fn main() { - let c = CustomSmartPointer { data: String::from("some data") }; - println!("CustomSmartPointer created."); - drop(c); - println!("CustomSmartPointer dropped before the end of main."); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-16/src/main.rs:here}} ``` Listing 15-16: Calling `std::mem::drop` to explicitly @@ -164,9 +124,7 @@ drop a value before it goes out of scope Running this code will print the following: ```text -CustomSmartPointer created. -Dropping CustomSmartPointer with data `some data`! -CustomSmartPointer dropped before the end of main. +{{#include ../listings/ch15-smart-pointers/listing-15-16/output.txt}} ``` The text ```Dropping CustomSmartPointer with data `some data`!``` is printed diff --git a/src/doc/book/src/ch15-04-rc.md b/src/doc/book/src/ch15-04-rc.md index 7ac901bad3..8990ca0460 100644 --- a/src/doc/book/src/ch15-04-rc.md +++ b/src/doc/book/src/ch15-04-rc.md @@ -51,20 +51,7 @@ won’t work, as shown in Listing 15-17: Filename: src/main.rs ```rust,ignore,does_not_compile -enum List { - Cons(i32, Box), - Nil, -} - -use crate::List::{Cons, Nil}; - -fn main() { - let a = Cons(5, - Box::new(Cons(10, - Box::new(Nil)))); - let b = Cons(3, Box::new(a)); - let c = Cons(4, Box::new(a)); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-17/src/main.rs}} ``` Listing 15-17: Demonstrating we’re not allowed to have @@ -73,16 +60,7 @@ two lists using `Box` that try to share ownership of a third list When we compile this code, we get this error: ```text -error[E0382]: use of moved value: `a` - --> src/main.rs:13:30 - | -12 | let b = Cons(3, Box::new(a)); - | - value moved here -13 | let c = Cons(4, Box::new(a)); - | ^ value used here after move - | - = note: move occurs because `a` has type `List`, which does not implement - the `Copy` trait +{{#include ../listings/ch15-smart-pointers/listing-15-17/output.txt}} ``` The `Cons` variants own the data they hold, so when we create the `b` list, `a` @@ -110,19 +88,7 @@ it. Filename: src/main.rs ```rust -enum List { - Cons(i32, Rc), - Nil, -} - -use crate::List::{Cons, Nil}; -use std::rc::Rc; - -fn main() { - let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); - let b = Cons(3, Rc::clone(&a)); - let c = Cons(4, Rc::clone(&a)); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-18/src/main.rs}} ``` Listing 15-18: A definition of `List` that uses @@ -156,25 +122,7 @@ then we can see how the reference count changes when `c` goes out of scope. Filename: src/main.rs ```rust -# enum List { -# Cons(i32, Rc), -# Nil, -# } -# -# use crate::List::{Cons, Nil}; -# use std::rc::Rc; -# -fn main() { - let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); - println!("count after creating a = {}", Rc::strong_count(&a)); - let b = Cons(3, Rc::clone(&a)); - println!("count after creating b = {}", Rc::strong_count(&a)); - { - let c = Cons(4, Rc::clone(&a)); - println!("count after creating c = {}", Rc::strong_count(&a)); - } - println!("count after c goes out of scope = {}", Rc::strong_count(&a)); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-19/src/main.rs:here}} ``` Listing 15-19: Printing the reference count @@ -189,10 +137,7 @@ type also has a `weak_count`; we’ll see what `weak_count` is used for in the This code prints the following: ```text -count after creating a = 1 -count after creating b = 2 -count after creating c = 3 -count after c goes out of scope = 2 +{{#include ../listings/ch15-smart-pointers/listing-15-19/output.txt}} ``` We can see that the `Rc` in `a` has an initial reference count of 1; then diff --git a/src/doc/book/src/ch15-05-interior-mutability.md b/src/doc/book/src/ch15-05-interior-mutability.md index 34c002b2fa..959d3eb7d8 100644 --- a/src/doc/book/src/ch15-05-interior-mutability.md +++ b/src/doc/book/src/ch15-05-interior-mutability.md @@ -76,22 +76,13 @@ A consequence of the borrowing rules is that when you have an immutable value, you can’t borrow it mutably. For example, this code won’t compile: ```rust,ignore,does_not_compile -fn main() { - let x = 5; - let y = &mut x; -} +{{#rustdoc_include ../listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs}} ``` If you tried to compile this code, you’d get the following error: ```text -error[E0596]: cannot borrow immutable local variable `x` as mutable - --> src/main.rs:3:18 - | -2 | let x = 5; - | - consider changing this to `mut x` -3 | let y = &mut x; - | ^ cannot borrow mutably +{{#include ../listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt}} ``` However, there are situations in which it would be useful for a value to mutate @@ -134,40 +125,7 @@ called `Messenger`. Listing 15-20 shows the library code: Filename: src/lib.rs ```rust -pub trait Messenger { - fn send(&self, msg: &str); -} - -pub struct LimitTracker<'a, T: Messenger> { - messenger: &'a T, - value: usize, - max: usize, -} - -impl<'a, T> LimitTracker<'a, T> - where T: Messenger { - pub fn new(messenger: &T, max: usize) -> LimitTracker { - LimitTracker { - messenger, - value: 0, - max, - } - } - - pub fn set_value(&mut self, value: usize) { - self.value = value; - - let percentage_of_max = self.value as f64 / self.max as f64; - - if percentage_of_max >= 1.0 { - self.messenger.send("Error: You are over your quota!"); - } else if percentage_of_max >= 0.9 { - self.messenger.send("Urgent warning: You've used up over 90% of your quota!"); - } else if percentage_of_max >= 0.75 { - self.messenger.send("Warning: You've used up over 75% of your quota!"); - } - } -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-20/src/lib.rs}} ``` Listing 15-20: A library to keep track of how close a @@ -194,36 +152,7 @@ implement a mock object to do just that, but the borrow checker won’t allow it Filename: src/lib.rs ```rust,ignore,does_not_compile -#[cfg(test)] -mod tests { - use super::*; - - struct MockMessenger { - sent_messages: Vec, - } - - impl MockMessenger { - fn new() -> MockMessenger { - MockMessenger { sent_messages: vec![] } - } - } - - impl Messenger for MockMessenger { - fn send(&self, message: &str) { - self.sent_messages.push(String::from(message)); - } - } - - #[test] - fn it_sends_an_over_75_percent_warning_message() { - let mock_messenger = MockMessenger::new(); - let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); - - limit_tracker.set_value(80); - - assert_eq!(mock_messenger.sent_messages.len(), 1); - } -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-21/src/lib.rs:here}} ``` Listing 15-21: An attempt to implement a `MockMessenger` @@ -250,13 +179,7 @@ of should now have one message in it. However, there’s one problem with this test, as shown here: ```text -error[E0596]: cannot borrow immutable field `self.sent_messages` as mutable - --> src/lib.rs:52:13 - | -51 | fn send(&self, message: &str) { - | ----- use `&mut self` here to make mutable -52 | self.sent_messages.push(String::from(message)); - | ^^^^^^^^^^^^^^^^^^ cannot mutably borrow immutable field +{{#include ../listings/ch15-smart-pointers/listing-15-21/output.txt}} ``` We can’t modify the `MockMessenger` to keep track of the messages, because the @@ -273,73 +196,7 @@ shows what that looks like: Filename: src/lib.rs ```rust -# pub trait Messenger { -# fn send(&self, msg: &str); -# } -# -# pub struct LimitTracker<'a, T: Messenger> { -# messenger: &'a T, -# value: usize, -# max: usize, -# } -# -# impl<'a, T> LimitTracker<'a, T> -# where T: Messenger { -# pub fn new(messenger: &T, max: usize) -> LimitTracker { -# LimitTracker { -# messenger, -# value: 0, -# max, -# } -# } -# -# pub fn set_value(&mut self, value: usize) { -# self.value = value; -# -# let percentage_of_max = self.value as f64 / self.max as f64; -# -# if percentage_of_max >= 1.0 { -# self.messenger.send("Error: You are over your quota!"); -# } else if percentage_of_max >= 0.9 { -# self.messenger.send("Urgent warning: You've used up over 90% of your quota!"); -# } else if percentage_of_max >= 0.75 { -# self.messenger.send("Warning: You've used up over 75% of your quota!"); -# } -# } -# } -# -#[cfg(test)] -mod tests { - use super::*; - use std::cell::RefCell; - - struct MockMessenger { - sent_messages: RefCell>, - } - - impl MockMessenger { - fn new() -> MockMessenger { - MockMessenger { sent_messages: RefCell::new(vec![]) } - } - } - - impl Messenger for MockMessenger { - fn send(&self, message: &str) { - self.sent_messages.borrow_mut().push(String::from(message)); - } - } - - #[test] - fn it_sends_an_over_75_percent_warning_message() { - // --snip-- -# let mock_messenger = MockMessenger::new(); -# let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); -# limit_tracker.set_value(75); - - assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); - } -} -# fn main() {} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-22/src/lib.rs:here}} ``` Listing 15-22: Using `RefCell` to mutate an inner @@ -388,15 +245,7 @@ at runtime. Filename: src/lib.rs ```rust,ignore,panics -impl Messenger for MockMessenger { - fn send(&self, message: &str) { - let mut one_borrow = self.sent_messages.borrow_mut(); - let mut two_borrow = self.sent_messages.borrow_mut(); - - one_borrow.push(String::from(message)); - two_borrow.push(String::from(message)); - } -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-23/src/lib.rs:here}} ``` Listing 15-23: Creating two mutable references in the @@ -409,10 +258,7 @@ which isn’t allowed. When we run the tests for our library, the code in Listin 15-23 will compile without any errors, but the test will fail: ```text ----- tests::it_sends_an_over_75_percent_warning_message stdout ---- - thread 'tests::it_sends_an_over_75_percent_warning_message' panicked at -'already borrowed: BorrowMutError', src/libcore/result.rs:906:4 -note: Run with `RUST_BACKTRACE=1` for a backtrace. +{{#include ../listings/ch15-smart-pointers/listing-15-23/output.txt}} ``` Notice that the code panicked with the message `already borrowed: @@ -447,30 +293,7 @@ the lists: Filename: src/main.rs ```rust -#[derive(Debug)] -enum List { - Cons(Rc>, Rc), - Nil, -} - -use crate::List::{Cons, Nil}; -use std::rc::Rc; -use std::cell::RefCell; - -fn main() { - let value = Rc::new(RefCell::new(5)); - - let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); - - let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); - let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); - - *value.borrow_mut() += 10; - - println!("a after = {:?}", a); - println!("b after = {:?}", b); - println!("c after = {:?}", c); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-24/src/main.rs}} ``` Listing 15-24: Using `Rc>` to create a @@ -498,9 +321,7 @@ When we print `a`, `b`, and `c`, we can see that they all have the modified value of 15 rather than 5: ```text -a after = Cons(RefCell { value: 15 }, Nil) -b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) -c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) +{{#include ../listings/ch15-smart-pointers/listing-15-24/output.txt}} ``` This technique is pretty neat! By using `RefCell`, we have an outwardly diff --git a/src/doc/book/src/ch15-06-reference-cycles.md b/src/doc/book/src/ch15-06-reference-cycles.md index 1a919e3a67..a824ec3ea2 100644 --- a/src/doc/book/src/ch15-06-reference-cycles.md +++ b/src/doc/book/src/ch15-06-reference-cycles.md @@ -17,29 +17,8 @@ starting with the definition of the `List` enum and a `tail` method in Listing Filename: src/main.rs - - ```rust -# fn main() {} -use std::rc::Rc; -use std::cell::RefCell; -use crate::List::{Cons, Nil}; - -#[derive(Debug)] -enum List { - Cons(i32, RefCell>), - Nil, -} - -impl List { - fn tail(&self) -> Option<&RefCell>> { - match self { - Cons(_, item) => Some(item), - Nil => None, - } - } -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-25/src/main.rs}} ``` Listing 15-25: A cons list definition that holds a @@ -61,47 +40,7 @@ reference counts are at various points in this process. Filename: src/main.rs ```rust -# use crate::List::{Cons, Nil}; -# use std::rc::Rc; -# use std::cell::RefCell; -# #[derive(Debug)] -# enum List { -# Cons(i32, RefCell>), -# Nil, -# } -# -# impl List { -# fn tail(&self) -> Option<&RefCell>> { -# match self { -# Cons(_, item) => Some(item), -# Nil => None, -# } -# } -# } -# -fn main() { - let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); - - println!("a initial rc count = {}", Rc::strong_count(&a)); - println!("a next item = {:?}", a.tail()); - - let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); - - println!("a rc count after b creation = {}", Rc::strong_count(&a)); - println!("b initial rc count = {}", Rc::strong_count(&b)); - println!("b next item = {:?}", b.tail()); - - if let Some(link) = a.tail() { - *link.borrow_mut() = Rc::clone(&b); - } - - println!("b rc count after changing a = {}", Rc::strong_count(&b)); - println!("a rc count after changing a = {}", Rc::strong_count(&a)); - - // Uncomment the next line to see that we have a cycle; - // it will overflow the stack - // println!("a next item = {:?}", a.tail()); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-26/src/main.rs:here}} ``` Listing 15-26: Creating a reference cycle of two `List` @@ -122,13 +61,7 @@ When we run this code, keeping the last `println!` commented out for the moment, we’ll get this output: ```text -a initial rc count = 1 -a next item = Some(RefCell { value: Nil }) -a rc count after b creation = 2 -b initial rc count = 1 -b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) }) -b rc count after changing a = 2 -a rc count after changing a = 2 +{{#include ../listings/ch15-smart-pointers/listing-15-26/output.txt}} ``` The reference count of the `Rc` instances in both `a` and `b` are 2 @@ -198,9 +131,9 @@ anything with the value that a `Weak` is pointing to, you must make sure the value still exists. Do this by calling the `upgrade` method on a `Weak` instance, which will return an `Option>`. You’ll get a result of `Some` if the `Rc` value has not been dropped yet and a result of `None` if the -`Rc` value has been dropped. Because `upgrade` returns an `Option`, Rust -will ensure that the `Some` case and the `None` case are handled, and there -won’t be an invalid pointer. +`Rc` value has been dropped. Because `upgrade` returns an `Option>`, +Rust will ensure that the `Some` case and the `None` case are handled, and +there won’t be an invalid pointer. As an example, rather than using a list whose items know only about the next item, we’ll create a tree whose items know about their children items *and* @@ -215,14 +148,7 @@ references to its children `Node` values: Filename: src/main.rs ```rust -use std::rc::Rc; -use std::cell::RefCell; - -#[derive(Debug)] -struct Node { - value: i32, - children: RefCell>>, -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-27/src/main.rs:here}} ``` We want a `Node` to own its children, and we want to share that ownership with @@ -238,26 +164,7 @@ with the value 5 and `leaf` as one of its children, as shown in Listing 15-27: Filename: src/main.rs ```rust -# use std::rc::Rc; -# use std::cell::RefCell; -# -# #[derive(Debug)] -# struct Node { -# value: i32, -# children: RefCell>>, -# } -# -fn main() { - let leaf = Rc::new(Node { - value: 3, - children: RefCell::new(vec![]), - }); - - let branch = Rc::new(Node { - value: 5, - children: RefCell::new(vec![Rc::clone(&leaf)]), - }); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-27/src/main.rs:there}} ``` Listing 15-27: Creating a `leaf` node with no children @@ -291,15 +198,7 @@ like this: Filename: src/main.rs ```rust -use std::rc::{Rc, Weak}; -use std::cell::RefCell; - -#[derive(Debug)] -struct Node { - value: i32, - parent: RefCell>, - children: RefCell>>, -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-28/src/main.rs:here}} ``` A node will be able to refer to its parent node but doesn’t own its parent. @@ -309,35 +208,7 @@ node will have a way to refer to its parent, `branch`: Filename: src/main.rs ```rust -# use std::rc::{Rc, Weak}; -# use std::cell::RefCell; -# -# #[derive(Debug)] -# struct Node { -# value: i32, -# parent: RefCell>, -# children: RefCell>>, -# } -# -fn main() { - let leaf = Rc::new(Node { - value: 3, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![]), - }); - - println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); - - let branch = Rc::new(Node { - value: 5, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![Rc::clone(&leaf)]), - }); - - *leaf.parent.borrow_mut() = Rc::downgrade(&branch); - - println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-28/src/main.rs:there}} ``` Listing 15-28: A `leaf` node with a weak reference to its @@ -390,58 +261,7 @@ in Listing 15-29: Filename: src/main.rs ```rust -# use std::rc::{Rc, Weak}; -# use std::cell::RefCell; -# -# #[derive(Debug)] -# struct Node { -# value: i32, -# parent: RefCell>, -# children: RefCell>>, -# } -# -fn main() { - let leaf = Rc::new(Node { - value: 3, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![]), - }); - - println!( - "leaf strong = {}, weak = {}", - Rc::strong_count(&leaf), - Rc::weak_count(&leaf), - ); - - { - let branch = Rc::new(Node { - value: 5, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![Rc::clone(&leaf)]), - }); - - *leaf.parent.borrow_mut() = Rc::downgrade(&branch); - - println!( - "branch strong = {}, weak = {}", - Rc::strong_count(&branch), - Rc::weak_count(&branch), - ); - - println!( - "leaf strong = {}, weak = {}", - Rc::strong_count(&leaf), - Rc::weak_count(&leaf), - ); - } - - println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); - println!( - "leaf strong = {}, weak = {}", - Rc::strong_count(&leaf), - Rc::weak_count(&leaf), - ); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-29/src/main.rs:here}} ``` Listing 15-29: Creating `branch` in an inner scope and @@ -492,7 +312,7 @@ If this chapter has piqued your interest and you want to implement your own smart pointers, check out [“The Rustonomicon”][nomicon] for more useful information. -[nomicon]: https://doc.rust-lang.org/stable/nomicon/ - Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new smart pointers. + +[nomicon]: ../nomicon/index.html diff --git a/src/doc/book/src/ch16-01-threads.md b/src/doc/book/src/ch16-01-threads.md index 5f6eb41a0b..6cec741d8c 100644 --- a/src/doc/book/src/ch16-01-threads.md +++ b/src/doc/book/src/ch16-01-threads.md @@ -71,22 +71,7 @@ thread and other text from a new thread: Filename: src/main.rs ```rust -use std::thread; -use std::time::Duration; - -fn main() { - thread::spawn(|| { - for i in 1..10 { - println!("hi number {} from the spawned thread!", i); - thread::sleep(Duration::from_millis(1)); - } - }); - - for i in 1..5 { - println!("hi number {} from the main thread!", i); - thread::sleep(Duration::from_millis(1)); - } -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-01/src/main.rs}} ``` Listing 16-1: Creating a new thread to print one thing @@ -97,6 +82,10 @@ thread ends, whether or not it has finished running. The output from this program might be a little different every time, but it will look similar to the following: + + ```text hi number 1 from the main thread! hi number 1 from the spawned thread! @@ -139,24 +128,7 @@ in Listing 16-1 and call `join` to make sure the spawned thread finishes before Filename: src/main.rs ```rust -use std::thread; -use std::time::Duration; - -fn main() { - let handle = thread::spawn(|| { - for i in 1..10 { - println!("hi number {} from the spawned thread!", i); - thread::sleep(Duration::from_millis(1)); - } - }); - - for i in 1..5 { - println!("hi number {} from the main thread!", i); - thread::sleep(Duration::from_millis(1)); - } - - handle.join().unwrap(); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-02/src/main.rs}} ``` Listing 16-2: Saving a `JoinHandle` from `thread::spawn` @@ -168,6 +140,10 @@ thread is prevented from performing work or exiting. Because we’ve put the cal to `join` after the main thread’s `for` loop, running Listing 16-2 should produce output similar to this: + + ```text hi number 1 from the main thread! hi number 2 from the main thread! @@ -193,29 +169,16 @@ But let’s see what happens when we instead move `handle.join()` before the Filename: src/main.rs ```rust -use std::thread; -use std::time::Duration; - -fn main() { - let handle = thread::spawn(|| { - for i in 1..10 { - println!("hi number {} from the spawned thread!", i); - thread::sleep(Duration::from_millis(1)); - } - }); - - handle.join().unwrap(); - - for i in 1..5 { - println!("hi number {} from the main thread!", i); - thread::sleep(Duration::from_millis(1)); - } -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs}} ``` The main thread will wait for the spawned thread to finish and then run its `for` loop, so the output won’t be interleaved anymore, as shown here: + + ```text hi number 1 from the spawned thread! hi number 2 from the spawned thread! @@ -255,17 +218,7 @@ thread. However, this won’t yet work, as you’ll see in a moment. Filename: src/main.rs ```rust,ignore,does_not_compile -use std::thread; - -fn main() { - let v = vec![1, 2, 3]; - - let handle = thread::spawn(|| { - println!("Here's a vector: {:?}", v); - }); - - handle.join().unwrap(); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-03/src/main.rs}} ``` Listing 16-3: Attempting to use a vector created by the @@ -277,20 +230,7 @@ should be able to access `v` inside that new thread. But when we compile this example, we get the following error: ```text -error[E0373]: closure may outlive the current function, but it borrows `v`, -which is owned by the current function - --> src/main.rs:6:32 - | -6 | let handle = thread::spawn(|| { - | ^^ may outlive borrowed value `v` -7 | println!("Here's a vector: {:?}", v); - | - `v` is borrowed here - | -help: to force the closure to take ownership of `v` (and any other referenced -variables), use the `move` keyword - | -6 | let handle = thread::spawn(move || { - | ^^^^^^^ +{{#include ../listings/ch16-fearless-concurrency/listing-16-03/output.txt}} ``` Rust *infers* how to capture `v`, and because `println!` only needs a reference @@ -304,19 +244,7 @@ that won’t be valid: Filename: src/main.rs ```rust,ignore,does_not_compile -use std::thread; - -fn main() { - let v = vec![1, 2, 3]; - - let handle = thread::spawn(|| { - println!("Here's a vector: {:?}", v); - }); - - drop(v); // oh no! - - handle.join().unwrap(); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-04/src/main.rs}} ``` Listing 16-4: A thread with a closure that attempts to @@ -332,9 +260,12 @@ is also invalid. Oh no! To fix the compiler error in Listing 16-3, we can use the error message’s advice: + + ```text -help: to force the closure to take ownership of `v` (and any other referenced -variables), use the `move` keyword +help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword | 6 | let handle = thread::spawn(move || { | ^^^^^^^ @@ -348,17 +279,7 @@ should borrow the values. The modification to Listing 16-3 shown in Listing Filename: src/main.rs ```rust -use std::thread; - -fn main() { - let v = vec![1, 2, 3]; - - let handle = thread::spawn(move || { - println!("Here's a vector: {:?}", v); - }); - - handle.join().unwrap(); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-05/src/main.rs}} ``` Listing 16-5: Using the `move` keyword to force a closure @@ -372,17 +293,7 @@ would move `v` into the closure’s environment, and we could no longer call `drop` on it in the main thread. We would get this compiler error instead: ```text -error[E0382]: use of moved value: `v` - --> src/main.rs:10:10 - | -6 | let handle = thread::spawn(move || { - | ------- value moved (into closure) here -... -10 | drop(v); // oh no! - | ^ value used here after move - | - = note: move occurs because `v` has type `std::vec::Vec`, which does - not implement the `Copy` trait +{{#include ../listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt}} ``` Rust’s ownership rules have saved us again! We got an error from the code in diff --git a/src/doc/book/src/ch16-02-message-passing.md b/src/doc/book/src/ch16-02-message-passing.md index 6b5c23f87e..7fdbccc69d 100644 --- a/src/doc/book/src/ch16-02-message-passing.md +++ b/src/doc/book/src/ch16-02-message-passing.md @@ -36,11 +36,7 @@ want to send over the channel. Filename: src/main.rs ```rust,ignore,does_not_compile -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-06/src/main.rs}} ``` Listing 16-6: Creating a channel and assigning the two @@ -72,17 +68,7 @@ sending a chat message from one thread to another. Filename: src/main.rs ```rust -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let val = String::from("hi"); - tx.send(val).unwrap(); - }); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-07/src/main.rs}} ``` Listing 16-7: Moving `tx` to a spawned thread and sending @@ -107,20 +93,7 @@ end of the river or like getting a chat message. Filename: src/main.rs ```rust -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let val = String::from("hi"); - tx.send(val).unwrap(); - }); - - let received = rx.recv().unwrap(); - println!("Got: {}", received); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-08/src/main.rs}} ``` Listing 16-8: Receiving the value “hi” in the main thread @@ -148,6 +121,10 @@ thread is appropriate. When we run the code in Listing 16-8, we’ll see the value printed from the main thread: + + ```text Got: hi ``` @@ -167,21 +144,7 @@ this code isn’t allowed: Filename: src/main.rs ```rust,ignore,does_not_compile -use std::thread; -use std::sync::mpsc; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let val = String::from("hi"); - tx.send(val).unwrap(); - println!("val is {}", val); - }); - - let received = rx.recv().unwrap(); - println!("Got: {}", received); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-09/src/main.rs}} ``` Listing 16-9: Attempting to use `val` after we’ve sent it @@ -195,16 +158,7 @@ unexpected results due to inconsistent or nonexistent data. However, Rust gives us an error if we try to compile the code in Listing 16-9: ```text -error[E0382]: use of moved value: `val` - --> src/main.rs:10:31 - | -9 | tx.send(val).unwrap(); - | --- value moved here -10 | println!("val is {}", val); - | ^^^ value used here after move - | - = note: move occurs because `val` has type `std::string::String`, which does -not implement the `Copy` trait +{{#include ../listings/ch16-fearless-concurrency/listing-16-09/output.txt}} ``` Our concurrency mistake has caused a compile time error. The `send` function @@ -223,31 +177,7 @@ pause for a second between each message. Filename: src/main.rs ```rust -use std::thread; -use std::sync::mpsc; -use std::time::Duration; - -fn main() { - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let vals = vec![ - String::from("hi"), - String::from("from"), - String::from("the"), - String::from("thread"), - ]; - - for val in vals { - tx.send(val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } - }); - - for received in rx { - println!("Got: {}", received); - } -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-10/src/main.rs}} ``` Listing 16-10: Sending multiple messages and pausing @@ -265,6 +195,10 @@ printing it. When the channel is closed, iteration will end. When running the code in Listing 16-10, you should see the following output with a 1-second pause in between each line: + + ```text Got: hi Got: from @@ -286,50 +220,7 @@ so by cloning the transmitting half of the channel, as shown in Listing 16-11: Filename: src/main.rs ```rust -# use std::thread; -# use std::sync::mpsc; -# use std::time::Duration; -# -# fn main() { -// --snip-- - -let (tx, rx) = mpsc::channel(); - -let tx1 = mpsc::Sender::clone(&tx); -thread::spawn(move || { - let vals = vec![ - String::from("hi"), - String::from("from"), - String::from("the"), - String::from("thread"), - ]; - - for val in vals { - tx1.send(val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } -}); - -thread::spawn(move || { - let vals = vec![ - String::from("more"), - String::from("messages"), - String::from("for"), - String::from("you"), - ]; - - for val in vals { - tx.send(val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } -}); - -for received in rx { - println!("Got: {}", received); -} - -// --snip-- -# } +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-11/src/main.rs:here}} ``` Listing 16-11: Sending multiple messages from multiple @@ -343,6 +234,10 @@ messages to the receiving end of the channel. When you run the code, your output should look something like this: + + ```text Got: hi Got: more diff --git a/src/doc/book/src/ch16-03-shared-state.md b/src/doc/book/src/ch16-03-shared-state.md index c39d302b92..50ce56cc78 100644 --- a/src/doc/book/src/ch16-03-shared-state.md +++ b/src/doc/book/src/ch16-03-shared-state.md @@ -54,18 +54,7 @@ single-threaded context, as shown in Listing 16-12: Filename: src/main.rs ```rust -use std::sync::Mutex; - -fn main() { - let m = Mutex::new(5); - - { - let mut num = m.lock().unwrap(); - *num = 6; - } - - println!("m = {:?}", m); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-12/src/main.rs}} ``` Listing 16-12: Exploring the API of `Mutex` in a @@ -110,28 +99,7 @@ a compiler error, and we’ll use that error to learn more about using Filename: src/main.rs ```rust,ignore,does_not_compile -use std::sync::Mutex; -use std::thread; - -fn main() { - let counter = Mutex::new(0); - let mut handles = vec![]; - - for _ in 0..10 { - let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; - }); - handles.push(handle); - } - - for handle in handles { - handle.join().unwrap(); - } - - println!("Result: {}", *counter.lock().unwrap()); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-13/src/main.rs}} ``` Listing 16-13: Ten threads each increment a counter @@ -153,17 +121,7 @@ program. We hinted that this example wouldn’t compile. Now let’s find out why! ```text -error[E0382]: use of moved value: `counter` - --> src/main.rs:9:36 - | -9 | let handle = thread::spawn(move || { - | ^^^^^^^ value moved into closure here, -in previous iteration of loop -10 | let mut num = counter.lock().unwrap(); - | ------- use occurs due to use in closure - | - = note: move occurs because `counter` has type `std::sync::Mutex`, -which does not implement the `Copy` trait +{{#include ../listings/ch16-fearless-concurrency/listing-16-13/output.txt}} ``` The error message states that the `counter` value was moved in the previous @@ -183,30 +141,7 @@ errors, we’ll also switch back to using the `for` loop, and we’ll keep the Filename: src/main.rs ```rust,ignore,does_not_compile -use std::rc::Rc; -use std::sync::Mutex; -use std::thread; - -fn main() { - let counter = Rc::new(Mutex::new(0)); - let mut handles = vec![]; - - for _ in 0..10 { - let counter = Rc::clone(&counter); - let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; - }); - handles.push(handle); - } - - for handle in handles { - handle.join().unwrap(); - } - - println!("Result: {}", *counter.lock().unwrap()); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-14/src/main.rs}} ``` Listing 16-14: Attempting to use `Rc` to allow @@ -216,19 +151,7 @@ Once again, we compile and get... different errors! The compiler is teaching us a lot. ```text -error[E0277]: `std::rc::Rc>` cannot be sent between threads safely - --> src/main.rs:11:22 - | -11 | let handle = thread::spawn(move || { - | ^^^^^^^^^^^^^ `std::rc::Rc>` -cannot be sent between threads safely - | - = help: within `[closure@src/main.rs:11:36: 14:10 -counter:std::rc::Rc>]`, the trait `std::marker::Send` -is not implemented for `std::rc::Rc>` - = note: required because it appears within the type -`[closure@src/main.rs:11:36: 14:10 counter:std::rc::Rc>]` - = note: required by `std::thread::spawn` +{{#include ../listings/ch16-fearless-concurrency/listing-16-14/output.txt}} ``` Wow, that error message is very wordy! Here’s the important part to focus @@ -271,29 +194,7 @@ our program by changing the `use` line, the call to `new`, and the call to Filename: src/main.rs ```rust -use std::sync::{Mutex, Arc}; -use std::thread; - -fn main() { - let counter = Arc::new(Mutex::new(0)); - let mut handles = vec![]; - - for _ in 0..10 { - let counter = Arc::clone(&counter); - let handle = thread::spawn(move || { - let mut num = counter.lock().unwrap(); - - *num += 1; - }); - handles.push(handle); - } - - for handle in handles { - handle.join().unwrap(); - } - - println!("Result: {}", *counter.lock().unwrap()); -} +{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-15/src/main.rs}} ``` Listing 16-15: Using an `Arc` to wrap the `Mutex` @@ -301,6 +202,10 @@ to be able to share ownership across multiple threads This code will print the following: + + ```text Result: 10 ``` diff --git a/src/doc/book/src/ch16-04-extensible-concurrency-sync-and-send.md b/src/doc/book/src/ch16-04-extensible-concurrency-sync-and-send.md index ff9830e38c..797f69a991 100644 --- a/src/doc/book/src/ch16-04-extensible-concurrency-sync-and-send.md +++ b/src/doc/book/src/ch16-04-extensible-concurrency-sync-and-send.md @@ -55,12 +55,10 @@ useful for enforcing invariants related to concurrency. Manually implementing these traits involves implementing unsafe Rust code. We’ll talk about using unsafe Rust code in Chapter 19; for now, the important information is that building new concurrent types not made up of `Send` and -`Sync` parts requires careful thought to uphold the safety guarantees. -[The Rustonomicon] has more information about these guarantees and how to +`Sync` parts requires careful thought to uphold the safety guarantees. [“The +Rustonomicon”][nomicon] has more information about these guarantees and how to uphold them. -[The Rustonomicon]: https://doc.rust-lang.org/stable/nomicon/ - ## Summary This isn’t the last you’ll see of concurrency in this book: the project in @@ -88,3 +86,4 @@ relate to those you might be familiar with from object-oriented programming. [sharing-a-mutext-between-multiple-threads]: ch16-03-shared-state.html#sharing-a-mutext-between-multiple-threads +[nomicon]: ../nomicon/index.html diff --git a/src/doc/book/src/ch17-01-what-is-oo.md b/src/doc/book/src/ch17-01-what-is-oo.md index 15eae18e94..e197cbfa84 100644 --- a/src/doc/book/src/ch17-01-what-is-oo.md +++ b/src/doc/book/src/ch17-01-what-is-oo.md @@ -47,10 +47,7 @@ cache the calculated average for us. Listing 17-1 has the definition of the Filename: src/lib.rs ```rust -pub struct AveragedCollection { - list: Vec, - average: f64, -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-01/src/lib.rs}} ``` Listing 17-1: An `AveragedCollection` struct that @@ -66,36 +63,7 @@ on the struct, as shown in Listing 17-2: Filename: src/lib.rs ```rust -# pub struct AveragedCollection { -# list: Vec, -# average: f64, -# } -impl AveragedCollection { - pub fn add(&mut self, value: i32) { - self.list.push(value); - self.update_average(); - } - - pub fn remove(&mut self) -> Option { - let result = self.list.pop(); - match result { - Some(value) => { - self.update_average(); - Some(value) - }, - None => None, - } - } - - pub fn average(&self) -> f64 { - self.average - } - - fn update_average(&mut self) { - let total: i32 = self.list.iter().sum(); - self.average = total as f64 / self.list.len() as f64; - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-02/src/lib.rs:here}} ``` Listing 17-2: Implementations of the public methods diff --git a/src/doc/book/src/ch17-02-trait-objects.md b/src/doc/book/src/ch17-02-trait-objects.md index d7369bffa1..b4f7e4287e 100644 --- a/src/doc/book/src/ch17-02-trait-objects.md +++ b/src/doc/book/src/ch17-02-trait-objects.md @@ -69,9 +69,7 @@ Listing 17-3 shows how to define a trait named `Draw` with one method named Filename: src/lib.rs ```rust -pub trait Draw { - fn draw(&self); -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-03/src/lib.rs}} ``` Listing 17-3: Definition of the `Draw` trait @@ -85,13 +83,7 @@ a `Box` that implements the `Draw` trait. Filename: src/lib.rs ```rust -# pub trait Draw { -# fn draw(&self); -# } -# -pub struct Screen { - pub components: Vec>, -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-04/src/lib.rs:here}} ``` Listing 17-4: Definition of the `Screen` struct with a @@ -104,21 +96,7 @@ On the `Screen` struct, we’ll define a method named `run` that will call the Filename: src/lib.rs ```rust -# pub trait Draw { -# fn draw(&self); -# } -# -# pub struct Screen { -# pub components: Vec>, -# } -# -impl Screen { - pub fn run(&self) { - for component in self.components.iter() { - component.draw(); - } - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-05/src/lib.rs:here}} ``` Listing 17-5: A `run` method on `Screen` that calls the @@ -134,22 +112,7 @@ as in Listing 17-6: Filename: src/lib.rs ```rust -# pub trait Draw { -# fn draw(&self); -# } -# -pub struct Screen { - pub components: Vec, -} - -impl Screen - where T: Draw { - pub fn run(&self) { - for component in self.components.iter() { - component.draw(); - } - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-06/src/lib.rs:here}} ``` Listing 17-6: An alternate implementation of the `Screen` @@ -176,21 +139,7 @@ might have fields for `width`, `height`, and `label`, as shown in Listing 17-7: Filename: src/lib.rs ```rust -# pub trait Draw { -# fn draw(&self); -# } -# -pub struct Button { - pub width: u32, - pub height: u32, - pub label: String, -} - -impl Draw for Button { - fn draw(&self) { - // code to actually draw a button - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-07/src/lib.rs:here}} ``` Listing 17-7: A `Button` struct that implements the @@ -213,19 +162,7 @@ If someone using our library decides to implement a `SelectBox` struct that has Filename: src/main.rs ```rust,ignore -use gui::Draw; - -struct SelectBox { - width: u32, - height: u32, - options: Vec, -} - -impl Draw for SelectBox { - fn draw(&self) { - // code to actually draw a select box - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-08/src/main.rs:here}} ``` Listing 17-8: Another crate using `gui` and implementing @@ -240,30 +177,7 @@ components. Listing 17-9 shows this implementation: Filename: src/main.rs ```rust,ignore -use gui::{Screen, Button}; - -fn main() { - let screen = Screen { - components: vec![ - Box::new(SelectBox { - width: 75, - height: 10, - options: vec![ - String::from("Yes"), - String::from("Maybe"), - String::from("No") - ], - }), - Box::new(Button { - width: 50, - height: 10, - label: String::from("OK"), - }), - ], - }; - - screen.run(); -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-09/src/main.rs:here}} ``` Listing 17-9: Using trait objects to store values of @@ -297,17 +211,7 @@ with a `String` as a component: Filename: src/main.rs ```rust,ignore,does_not_compile -use gui::Screen; - -fn main() { - let screen = Screen { - components: vec![ - Box::new(String::from("Hi")), - ], - }; - - screen.run(); -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-10/src/main.rs}} ``` Listing 17-10: Attempting to use a type that doesn’t @@ -316,14 +220,7 @@ implement the trait object’s trait We’ll get this error because `String` doesn’t implement the `Draw` trait: ```text -error[E0277]: the trait bound `std::string::String: gui::Draw` is not satisfied - --> src/main.rs:7:13 - | - 7 | Box::new(String::from("Hi")), - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait gui::Draw is not - implemented for `std::string::String` - | - = note: required for the cast to the object type `gui::Draw` +{{#include ../listings/ch17-oop/listing-17-10/output.txt}} ``` This error lets us know that either we’re passing something to `Screen` we @@ -398,22 +295,13 @@ tried to implement the `Screen` struct in Listing 17-4 to hold types that implement the `Clone` trait instead of the `Draw` trait, like this: ```rust,ignore,does_not_compile -pub struct Screen { - pub components: Vec>, -} +{{#rustdoc_include ../listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs}} ``` We would get this error: ```text -error[E0038]: the trait `std::clone::Clone` cannot be made into an object - --> src/lib.rs:2:5 - | -2 | pub components: Vec>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` - cannot be made into an object - | - = note: the trait cannot require that `Self : Sized` +{{#include ../listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt}} ``` This error means you can’t use this trait as a trait object in this way. If diff --git a/src/doc/book/src/ch17-03-oo-design-patterns.md b/src/doc/book/src/ch17-03-oo-design-patterns.md index 4ffb3a0179..8807541346 100644 --- a/src/doc/book/src/ch17-03-oo-design-patterns.md +++ b/src/doc/book/src/ch17-03-oo-design-patterns.md @@ -34,21 +34,8 @@ because we haven’t implemented the `blog` crate yet. Filename: src/main.rs -```rust,ignore -use blog::Post; - -fn main() { - let mut post = Post::new(); - - post.add_text("I ate a salad for lunch today"); - assert_eq!("", post.content()); - - post.request_review(); - assert_eq!("", post.content()); - - post.approve(); - assert_eq!("I ate a salad for lunch today", post.content()); -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch17-oop/listing-17-11/src/main.rs:all}} ``` Listing 17-11: Code that demonstrates the desired @@ -89,25 +76,7 @@ inside an `Option` in a private field named `state`. You’ll see why the Filename: src/lib.rs ```rust -pub struct Post { - state: Option>, - content: String, -} - -impl Post { - pub fn new() -> Post { - Post { - state: Some(Box::new(Draft {})), - content: String::new(), - } - } -} - -trait State {} - -struct Draft {} - -impl State for Draft {} +{{#rustdoc_include ../listings/ch17-oop/listing-17-12/src/lib.rs}} ``` Listing 17-12: Definition of a `Post` struct and a `new` @@ -139,16 +108,7 @@ Post` block: Filename: src/lib.rs ```rust -# pub struct Post { -# content: String, -# } -# -impl Post { - // --snip-- - pub fn add_text(&mut self, text: &str) { - self.content.push_str(text); - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-13/src/lib.rs:here}} ``` Listing 17-13: Implementing the `add_text` method to add @@ -176,16 +136,7 @@ be empty. Listing 17-14 shows this placeholder implementation: Filename: src/lib.rs ```rust -# pub struct Post { -# content: String, -# } -# -impl Post { - // --snip-- - pub fn content(&self) -> &str { - "" - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-14/src/lib.rs:here}} ``` Listing 17-14: Adding a placeholder implementation for @@ -202,39 +153,7 @@ change its state from `Draft` to `PendingReview`. Listing 17-15 shows this code: Filename: src/lib.rs ```rust -# pub struct Post { -# state: Option>, -# content: String, -# } -# -impl Post { - // --snip-- - pub fn request_review(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.request_review()) - } - } -} - -trait State { - fn request_review(self: Box) -> Box; -} - -struct Draft {} - -impl State for Draft { - fn request_review(self: Box) -> Box { - Box::new(PendingReview {}) - } -} - -struct PendingReview {} - -impl State for PendingReview { - fn request_review(self: Box) -> Box { - self - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-15/src/lib.rs:here}} ``` Listing 17-15: Implementing `request_review` methods on @@ -291,62 +210,7 @@ state is approved, as shown in Listing 17-16: Filename: src/lib.rs ```rust -# pub struct Post { -# state: Option>, -# content: String, -# } -# -impl Post { - // --snip-- - pub fn approve(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.approve()) - } - } -} - -trait State { - fn request_review(self: Box) -> Box; - fn approve(self: Box) -> Box; -} - -struct Draft {} - -impl State for Draft { -# fn request_review(self: Box) -> Box { -# Box::new(PendingReview {}) -# } -# - // --snip-- - fn approve(self: Box) -> Box { - self - } -} - -struct PendingReview {} - -impl State for PendingReview { -# fn request_review(self: Box) -> Box { -# self -# } -# - // --snip-- - fn approve(self: Box) -> Box { - Box::new(Published {}) - } -} - -struct Published {} - -impl State for Published { - fn request_review(self: Box) -> Box { - self - } - - fn approve(self: Box) -> Box { - self - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-16/src/lib.rs:here}} ``` Listing 17-16: Implementing the `approve` method on @@ -368,22 +232,8 @@ otherwise, we want to return an empty string slice, as shown in Listing 17-17: Filename: src/lib.rs -```rust -# trait State { -# fn content<'a>(&self, post: &'a Post) -> &'a str; -# } -# pub struct Post { -# state: Option>, -# content: String, -# } -# -impl Post { - // --snip-- - pub fn content(&self) -> &str { - self.state.as_ref().unwrap().content(self) - } - // --snip-- -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch17-oop/listing-17-17/src/lib.rs:here}} ``` Listing 17-17: Updating the `content` method on `Post` to @@ -418,25 +268,7 @@ Listing 17-18: Filename: src/lib.rs ```rust -# pub struct Post { -# content: String -# } -trait State { - // --snip-- - fn content<'a>(&self, post: &'a Post) -> &'a str { - "" - } -} - -// --snip-- -struct Published {} - -impl State for Published { - // --snip-- - fn content<'a>(&self, post: &'a Post) -> &'a str { - &post.content - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-18/src/lib.rs:here}} ``` Listing 17-18: Adding the `content` method to the `State` @@ -528,14 +360,7 @@ Let’s consider the first part of `main` in Listing 17-11: Filename: src/main.rs ```rust,ignore -# use blog::Post; - -fn main() { - let mut post = Post::new(); - - post.add_text("I ate a salad for lunch today"); - assert_eq!("", post.content()); -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-11/src/main.rs:here}} ``` We still enable the creation of new posts in the draft state using `Post::new` @@ -551,31 +376,7 @@ as well as methods on each: Filename: src/lib.rs ```rust -pub struct Post { - content: String, -} - -pub struct DraftPost { - content: String, -} - -impl Post { - pub fn new() -> DraftPost { - DraftPost { - content: String::new(), - } - } - - pub fn content(&self) -> &str { - &self.content - } -} - -impl DraftPost { - pub fn add_text(&mut self, text: &str) { - self.content.push_str(text); - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-19/src/lib.rs}} ``` Listing 17-19: A `Post` with a `content` method and a @@ -611,35 +412,7 @@ shown in Listing 17-20: Filename: src/lib.rs ```rust -# pub struct Post { -# content: String, -# } -# -# pub struct DraftPost { -# content: String, -# } -# -impl DraftPost { - // --snip-- - - pub fn request_review(self) -> PendingReviewPost { - PendingReviewPost { - content: self.content, - } - } -} - -pub struct PendingReviewPost { - content: String, -} - -impl PendingReviewPost { - pub fn approve(self) -> Post { - Post { - content: self.content, - } - } -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-20/src/lib.rs:here}} ``` Listing 17-20: A `PendingReviewPost` that gets created by @@ -669,19 +442,7 @@ The updated code in `main` is shown in Listing 17-21: Filename: src/main.rs ```rust,ignore -use blog::Post; - -fn main() { - let mut post = Post::new(); - - post.add_text("I ate a salad for lunch today"); - - let post = post.request_review(); - - let post = post.approve(); - - assert_eq!("I ate a salad for lunch today", post.content()); -} +{{#rustdoc_include ../listings/ch17-oop/listing-17-21/src/main.rs}} ``` Listing 17-21: Modifications to `main` to use the new diff --git a/src/doc/book/src/ch18-01-all-the-places-for-patterns.md b/src/doc/book/src/ch18-01-all-the-places-for-patterns.md index d838532fba..ec0389a8d2 100644 --- a/src/doc/book/src/ch18-01-all-the-places-for-patterns.md +++ b/src/doc/book/src/ch18-01-all-the-places-for-patterns.md @@ -53,25 +53,7 @@ input. Filename: src/main.rs ```rust -fn main() { - let favorite_color: Option<&str> = None; - let is_tuesday = false; - let age: Result = "34".parse(); - - if let Some(color) = favorite_color { - println!("Using your favorite color, {}, as the background", color); - } else if is_tuesday { - println!("Tuesday is green day!"); - } else if let Ok(age) = age { - if age > 30 { - println!("Using purple as the background color"); - } else { - println!("Using orange as the background color"); - } - } else { - println!("Using blue as the background color"); - } -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-01/src/main.rs}} ``` Listing 18-1: Mixing `if let`, `else if`, `else if let`, @@ -108,15 +90,7 @@ Listing 18-2 shows a `while let` loop that uses a vector as a stack and prints the values in the vector in the opposite order in which they were pushed. ```rust -let mut stack = Vec::new(); - -stack.push(1); -stack.push(2); -stack.push(3); - -while let Some(top) = stack.pop() { - println!("{}", top); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-02/src/main.rs:here}} ``` Listing 18-2: Using a `while let` loop to print values @@ -139,11 +113,7 @@ Listing 18-3 demonstrates how to use a pattern in a `for` loop to destructure, or break apart, a tuple as part of the `for` loop. ```rust -let v = vec!['a', 'b', 'c']; - -for (index, value) in v.iter().enumerate() { - println!("{} is at index {}", value, index); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-03/src/main.rs:here}} ``` Listing 18-3: Using a pattern in a `for` loop to @@ -152,9 +122,7 @@ destructure a tuple The code in Listing 18-3 will print the following: ```text -a is at index 0 -b is at index 1 -c is at index 2 +{{#include ../listings/ch18-patterns-and-matching/listing-18-03/output.txt}} ``` We use the `enumerate` method to adapt an iterator to produce a value and that @@ -193,7 +161,7 @@ To see the pattern matching aspect of `let` more clearly, consider Listing 18-4, which uses a pattern with `let` to destructure a tuple. ```rust -let (x, y, z) = (1, 2, 3); +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-04/src/main.rs:here}} ``` Listing 18-4: Using a pattern to destructure a tuple and @@ -210,7 +178,7 @@ example, Listing 18-5 shows an attempt to destructure a tuple with three elements into two variables, which won’t work. ```rust,ignore,does_not_compile -let (x, y) = (1, 2, 3); +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-05/src/main.rs:here}} ``` Listing 18-5: Incorrectly constructing a pattern whose @@ -219,14 +187,7 @@ variables don’t match the number of elements in the tuple Attempting to compile this code results in this type error: ```text -error[E0308]: mismatched types - --> src/main.rs:2:9 - | -2 | let (x, y) = (1, 2, 3); - | ^^^^^^ expected a tuple with 3 elements, found one with 2 elements - | - = note: expected type `({integer}, {integer}, {integer})` - found type `(_, _)` +{{#include ../listings/ch18-patterns-and-matching/listing-18-05/output.txt}} ``` If we wanted to ignore one or more of the values in the tuple, we could use `_` @@ -243,9 +204,7 @@ declares a function named `foo` that takes one parameter named `x` of type `i32`, should by now look familiar. ```rust -fn foo(x: i32) { - // code goes here -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-06/src/main.rs:here}} ``` Listing 18-6: A function signature uses patterns in the @@ -258,14 +217,7 @@ as we pass it to a function. Filename: src/main.rs ```rust -fn print_coordinates(&(x, y): &(i32, i32)) { - println!("Current location: ({}, {})", x, y); -} - -fn main() { - let point = (3, 5); - print_coordinates(&point); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-07/src/main.rs}} ``` Listing 18-7: A function with parameters that destructure diff --git a/src/doc/book/src/ch18-02-refutability.md b/src/doc/book/src/ch18-02-refutability.md index 36fa17d48b..029547f4ad 100644 --- a/src/doc/book/src/ch18-02-refutability.md +++ b/src/doc/book/src/ch18-02-refutability.md @@ -28,7 +28,7 @@ where Rust requires an irrefutable pattern and vice versa. Listing 18-8 shows a pattern. As you might expect, this code will not compile. ```rust,ignore,does_not_compile -let Some(x) = some_option_value; +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-08/src/main.rs:here}} ``` Listing 18-8: Attempting to use a refutable pattern with @@ -41,11 +41,7 @@ do with a `None` value. At compile time, Rust will complain that we’ve tried t use a refutable pattern where an irrefutable pattern is required: ```text -error[E0005]: refutable pattern in local binding: `None` not covered - --> - | -3 | let Some(x) = some_option_value; - | ^^^^^^^ pattern `None` not covered +{{#include ../listings/ch18-patterns-and-matching/listing-18-08/output.txt}} ``` Because we didn’t cover (and couldn’t cover!) every valid value with the @@ -58,10 +54,7 @@ will just skip the code in the curly brackets, giving it a way to continue validly. Listing 18-9 shows how to fix the code in Listing 18-8. ```rust -# let some_option_value: Option = None; -if let Some(x) = some_option_value { - println!("{}", x); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-09/src/main.rs:here}} ``` Listing 18-9: Using `if let` and a block with refutable @@ -72,10 +65,8 @@ cannot use an irrefutable pattern without receiving an error. If we give `if let` a pattern that will always match, such as `x`, as shown in Listing 18-10, the compiler will give a warning. -```rust,ignore -if let x = 5 { - println!("{}", x); -}; +```rust +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-10/src/main.rs:here}} ``` Listing 18-10: Attempting to use an irrefutable pattern @@ -85,15 +76,7 @@ Rust complains that it doesn’t make sense to use `if let` with an irrefutable pattern: ```text -warning: irrefutable if-let pattern - --> :2:5 - | -2 | / if let x = 5 { -3 | | println!("{}", x); -4 | | }; - | |_^ - | - = note: #[warn(irrefutable_let_patterns)] on by default +{{#include ../listings/ch18-patterns-and-matching/listing-18-10/output.txt}} ``` For this reason, match arms must use refutable patterns, except for the last diff --git a/src/doc/book/src/ch18-03-pattern-syntax.md b/src/doc/book/src/ch18-03-pattern-syntax.md index ccbcbd9ad4..d0b281844f 100644 --- a/src/doc/book/src/ch18-03-pattern-syntax.md +++ b/src/doc/book/src/ch18-03-pattern-syntax.md @@ -10,14 +10,7 @@ As you saw in Chapter 6, you can match patterns against literals directly. The following code gives some examples: ```rust -let x = 1; - -match x { - 1 => println!("one"), - 2 => println!("two"), - 3 => println!("three"), - _ => println!("anything"), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/no-listing-01-literals/src/main.rs:here}} ``` This code prints `one` because the value in `x` is 1. This syntax is useful @@ -40,18 +33,7 @@ running this code or reading further. Filename: src/main.rs ```rust -fn main() { - let x = Some(5); - let y = 10; - - match x { - Some(50) => println!("Got 50"), - Some(y) => println!("Matched, y = {:?}", y), - _ => println!("Default case, x = {:?}", x), - } - - println!("at the end: x = {:?}, y = {:?}", x, y); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-11/src/main.rs:here}} ``` Listing 18-11: A `match` expression with an arm that @@ -94,13 +76,7 @@ value of `x` matches either of the values in that arm, that arm’s code will run: ```rust -let x = 1; - -match x { - 1 | 2 => println!("one or two"), - 3 => println!("three"), - _ => println!("anything"), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/no-listing-02-multiple-patterns/src/main.rs:here}} ``` This code prints `one or two`. @@ -112,12 +88,7 @@ following code, when a pattern matches any of the values within the range, that arm will execute: ```rust -let x = 5; - -match x { - 1..=5 => println!("one through five"), - _ => println!("something else"), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/no-listing-03-ranges/src/main.rs:here}} ``` If `x` is 1, 2, 3, 4, or 5, the first arm will match. This syntax is more @@ -133,13 +104,7 @@ which Rust can tell if a range is empty or not are `char` and numeric values. Here is an example using ranges of `char` values: ```rust -let x = 'c'; - -match x { - 'a'..='j' => println!("early ASCII letter"), - 'k'..='z' => println!("late ASCII letter"), - _ => println!("something else"), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/no-listing-04-ranges-of-char/src/main.rs:here}} ``` Rust can tell that `c` is within the first pattern’s range and prints `early @@ -158,18 +123,7 @@ break apart using a pattern with a `let` statement. Filename: src/main.rs ```rust -struct Point { - x: i32, - y: i32, -} - -fn main() { - let p = Point { x: 0, y: 7 }; - - let Point { x: a, y: b } = p; - assert_eq!(0, a); - assert_eq!(7, b); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-12/src/main.rs}} ``` Listing 18-12: Destructuring a struct’s fields into @@ -192,18 +146,7 @@ in Listing 18-12, but the variables created in the `let` pattern are `x` and Filename: src/main.rs ```rust -struct Point { - x: i32, - y: i32, -} - -fn main() { - let p = Point { x: 0, y: 7 }; - - let Point { x, y } = p; - assert_eq!(0, x); - assert_eq!(7, y); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-13/src/main.rs}} ``` Listing 18-13: Destructuring struct fields using struct @@ -225,20 +168,7 @@ three cases: points that lie directly on the `x` axis (which is true when `y = Filename: src/main.rs ```rust -# struct Point { -# x: i32, -# y: i32, -# } -# -fn main() { - let p = Point { x: 0, y: 7 }; - - match p { - Point { x, y: 0 } => println!("On the x axis at {}", x), - Point { x: 0, y } => println!("On the y axis at {}", y), - Point { x, y } => println!("On neither axis: ({}, {})", x, y), - } -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-14/src/main.rs:here}} ``` Listing 18-14: Destructuring and matching literal values @@ -268,38 +198,7 @@ a `match` with patterns that will destructure each inner value. Filename: src/main.rs ```rust -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(i32, i32, i32), -} - -fn main() { - let msg = Message::ChangeColor(0, 160, 255); - - match msg { - Message::Quit => { - println!("The Quit variant has no data to destructure.") - } - Message::Move { x, y } => { - println!( - "Move in the x direction {} and in the y direction {}", - x, - y - ); - } - Message::Write(text) => println!("Text message: {}", text), - Message::ChangeColor(r, g, b) => { - println!( - "Change the color to red {}, green {}, and blue {}", - r, - g, - b - ) - } - } -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-15/src/main.rs}} ``` Listing 18-15: Destructuring enum variants that hold @@ -333,41 +232,7 @@ For example, we can refactor the code in Listing 18-15 to support RGB and HSV colors in the `ChangeColor` message, as shown in Listing 18-16. ```rust -enum Color { - Rgb(i32, i32, i32), - Hsv(i32, i32, i32), -} - -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(Color), -} - -fn main() { - let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); - - match msg { - Message::ChangeColor(Color::Rgb(r, g, b)) => { - println!( - "Change the color to red {}, green {}, and blue {}", - r, - g, - b - ) - } - Message::ChangeColor(Color::Hsv(h, s, v)) => { - println!( - "Change the color to hue {}, saturation {}, and value {}", - h, - s, - v - ) - } - _ => () - } -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-16/src/main.rs}} ``` Listing 18-16: Matching on nested enums @@ -386,12 +251,7 @@ The following example shows a complicated destructure where we nest structs and tuples inside a tuple and destructure all the primitive values out: ```rust -# struct Point { -# x: i32, -# y: i32, -# } -# -let ((feet, inches), Point {x, y}) = ((3, 10), Point { x: 3, y: -10 }); +{{#rustdoc_include ../listings/ch18-patterns-and-matching/no-listing-05-destructuring-structs-and-tuples/src/main.rs:here}} ``` This code lets us break complex types into their component parts so we can use @@ -420,13 +280,7 @@ including function parameters, as shown in Listing 18-17. Filename: src/main.rs ```rust -fn foo(_: i32, y: i32) { - println!("This code only uses the y parameter: {}", y); -} - -fn main() { - foo(3, 4); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-17/src/main.rs}} ``` Listing 18-17: Using `_` in a function signature @@ -452,19 +306,7 @@ the user should not be allowed to overwrite an existing customization of a setting but can unset the setting and give it a value if it is currently unset. ```rust -let mut setting_value = Some(5); -let new_setting_value = Some(10); - -match (setting_value, new_setting_value) { - (Some(_), Some(_)) => { - println!("Can't overwrite an existing customized value"); - } - _ => { - setting_value = new_setting_value; - } -} - -println!("setting is {:?}", setting_value); +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-18/src/main.rs:here}} ``` Listing 18-18: Using an underscore within patterns that @@ -487,13 +329,7 @@ particular values. Listing 18-19 shows an example of ignoring the second and fourth values in a tuple of five items. ```rust -let numbers = (2, 4, 8, 16, 32); - -match numbers { - (first, _, third, _, fifth) => { - println!("Some numbers: {}, {}, {}", first, third, fifth) - }, -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-19/src/main.rs:here}} ``` Listing 18-19: Ignoring multiple parts of a tuple @@ -514,10 +350,7 @@ only get a warning about one of them. Filename: src/main.rs ```rust -fn main() { - let _x = 5; - let y = 10; -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-20/src/main.rs}} ``` Listing 18-20: Starting a variable name with an @@ -532,13 +365,7 @@ variable, whereas `_` doesn’t bind at all. To show a case where this distinction matters, Listing 18-21 will provide us with an error. ```rust,ignore,does_not_compile -let s = Some(String::from("Hello!")); - -if let Some(_s) = s { - println!("found a string"); -} - -println!("{:?}", s); +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-21/src/main.rs:here}} ``` Listing 18-21: An unused variable starting with an @@ -550,13 +377,7 @@ doesn’t ever bind to the value. Listing 18-22 will compile without any errors because `s` doesn’t get moved into `_`. ```rust -let s = Some(String::from("Hello!")); - -if let Some(_) = s { - println!("found a string"); -} - -println!("{:?}", s); +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-22/src/main.rs:here}} ``` Listing 18-22: Using an underscore does not bind the @@ -575,17 +396,7 @@ explicitly matched in the rest of the pattern. In Listing 18-23, we have a the values in the `y` and `z` fields. ```rust -struct Point { - x: i32, - y: i32, - z: i32, -} - -let origin = Point { x: 0, y: 0, z: 0 }; - -match origin { - Point { x, .. } => println!("x is {}", x), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-23/src/main.rs:here}} ``` Listing 18-23: Ignoring all fields of a `Point` except @@ -602,15 +413,7 @@ shows how to use `..` with a tuple. Filename: src/main.rs ```rust -fn main() { - let numbers = (2, 4, 8, 16, 32); - - match numbers { - (first, .., last) => { - println!("Some numbers: {}, {}", first, last); - }, - } -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-24/src/main.rs}} ``` Listing 18-24: Matching only the first and last values in @@ -627,15 +430,7 @@ compile. Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - let numbers = (2, 4, 8, 16, 32); - - match numbers { - (.., second, ..) => { - println!("Some numbers: {}", second) - }, - } -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-25/src/main.rs}} ``` Listing 18-25: An attempt to use `..` in an ambiguous @@ -644,11 +439,7 @@ way When we compile this example, we get this error: ```text -error: `..` can only be used once per tuple or tuple struct pattern - --> src/main.rs:5:22 - | -5 | (.., second, ..) => { - | ^^ +{{#include ../listings/ch18-patterns-and-matching/listing-18-25/output.txt}} ``` It’s impossible for Rust to determine how many values in the tuple to ignore @@ -671,13 +462,7 @@ The condition can use variables created in the pattern. Listing 18-26 shows a guard of `if x < 5`. ```rust -let num = Some(4); - -match num { - Some(x) if x < 5 => println!("less than five: {}", x), - Some(x) => println!("{}", x), - None => (), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-26/src/main.rs:here}} ``` Listing 18-26: Adding a match guard to a pattern @@ -705,18 +490,7 @@ problem. Filename: src/main.rs ```rust -fn main() { - let x = Some(5); - let y = 10; - - match x { - Some(50) => println!("Got 50"), - Some(n) if n == y => println!("Matched, n = {}", n), - _ => println!("Default case, x = {:?}", x), - } - - println!("at the end: x = {:?}, y = {}", x, y); -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-27/src/main.rs}} ``` Listing 18-27: Using a match guard to test for equality @@ -742,13 +516,7 @@ to `4`, `5`, *and* `6`, even though it might look like `if y` only applies to `6`. ```rust -let x = 4; -let y = false; - -match x { - 4 | 5 | 6 if y => println!("yes"), - _ => println!("no"), -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-28/src/main.rs:here}} ``` Listing 18-28: Combining multiple patterns with a match @@ -789,23 +557,7 @@ name this variable `id`, the same as the field, but for this example we’ll use a different name. ```rust -enum Message { - Hello { id: i32 }, -} - -let msg = Message::Hello { id: 5 }; - -match msg { - Message::Hello { id: id_variable @ 3..=7 } => { - println!("Found an id in range: {}", id_variable) - }, - Message::Hello { id: 10..=12 } => { - println!("Found an id in another range") - }, - Message::Hello { id } => { - println!("Found some other id: {}", id) - }, -} +{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-29/src/main.rs:here}} ``` Listing 18-29: Using `@` to bind to a value in a pattern diff --git a/src/doc/book/src/ch19-01-unsafe-rust.md b/src/doc/book/src/ch19-01-unsafe-rust.md index c7956e8627..653bf88b75 100644 --- a/src/doc/book/src/ch19-01-unsafe-rust.md +++ b/src/doc/book/src/ch19-01-unsafe-rust.md @@ -25,7 +25,7 @@ Rust and how to do it. ### Unsafe Superpowers To switch to unsafe Rust, use the `unsafe` keyword and then start a new block -that holds the unsafe code. You can take four actions in unsafe Rust, called +that holds the unsafe code. You can take five actions in unsafe Rust, called *unsafe superpowers*, that you can’t in safe Rust. Those superpowers include the ability to: @@ -38,7 +38,7 @@ the ability to: It’s important to understand that `unsafe` doesn’t turn off the borrow checker or disable any other of Rust’s safety checks: if you use a reference in unsafe code, it will still be checked. The `unsafe` keyword only gives you access to -these four features that are then not checked by the compiler for memory +these five features that are then not checked by the compiler for memory safety. You’ll still get some degree of safety inside of an unsafe block. In addition, `unsafe` does not mean the code inside the block is necessarily @@ -46,7 +46,7 @@ dangerous or that it will definitely have memory safety problems: the intent is that as the programmer, you’ll ensure the code inside an `unsafe` block will access memory in a valid way. -People are fallible, and mistakes will happen, but by requiring these four +People are fallible, and mistakes will happen, but by requiring these five unsafe operations to be inside blocks annotated with `unsafe` you’ll know that any errors related to memory safety must be within an `unsafe` block. Keep `unsafe` blocks small; you’ll be thankful later when you investigate memory @@ -61,7 +61,7 @@ from leaking out into all the places that you or your users might want to use the functionality implemented with `unsafe` code, because using a safe abstraction is safe. -Let’s look at each of the four unsafe superpowers in turn. We’ll also look at +Let’s look at each of the five unsafe superpowers in turn. We’ll also look at some abstractions that provide a safe interface to unsafe code. ### Dereferencing a Raw Pointer @@ -91,10 +91,7 @@ Listing 19-1 shows how to create an immutable and a mutable raw pointer from references. ```rust -let mut num = 5; - -let r1 = &num as *const i32; -let r2 = &mut num as *mut i32; +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-01/src/main.rs:here}} ``` Listing 19-1: Creating raw pointers from references @@ -117,8 +114,7 @@ is no memory access, or the program might error with a segmentation fault. Usually, there is no good reason to write code like this, but it is possible. ```rust -let address = 0x012345usize; -let r = address as *const i32; +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-02/src/main.rs:here}} ``` Listing 19-2: Creating a raw pointer to an arbitrary @@ -129,15 +125,7 @@ raw pointers and read the data being pointed to. In Listing 19-3, we use the dereference operator `*` on a raw pointer that requires an `unsafe` block. ```rust,unsafe -let mut num = 5; - -let r1 = &num as *const i32; -let r2 = &mut num as *mut i32; - -unsafe { - println!("r1 is: {}", *r1); - println!("r2 is: {}", *r2); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-03/src/main.rs:here}} ``` Listing 19-3: Dereferencing raw pointers within an @@ -178,22 +166,14 @@ Here is an unsafe function named `dangerous` that doesn’t do anything in its body: ```rust,unsafe -unsafe fn dangerous() {} - -unsafe { - dangerous(); -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-01-unsafe-fn/src/main.rs:here}} ``` We must call the `dangerous` function within a separate `unsafe` block. If we try to call `dangerous` without the `unsafe` block, we’ll get an error: ```text -error[E0133]: call to unsafe function requires unsafe function or block - --> - | -4 | dangerous(); - | ^^^^^^^^^^^ call to unsafe function +{{#include ../listings/ch19-advanced-features/output-only-01-missing-unsafe/output.txt}} ``` By inserting the `unsafe` block around our call to `dangerous`, we’re asserting @@ -216,14 +196,7 @@ slice and makes it two by splitting the slice at the index given as an argument. Listing 19-4 shows how to use `split_at_mut`. ```rust -let mut v = vec![1, 2, 3, 4, 5, 6]; - -let r = &mut v[..]; - -let (a, b) = r.split_at_mut(3); - -assert_eq!(a, &mut [1, 2, 3]); -assert_eq!(b, &mut [4, 5, 6]); +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-04/src/main.rs:here}} ``` Listing 19-4: Using the safe `split_at_mut` @@ -235,14 +208,7 @@ implement `split_at_mut` as a function rather than a method and only for slices of `i32` values rather than for a generic type `T`. ```rust,ignore,does_not_compile -fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { - let len = slice.len(); - - assert!(mid <= len); - - (&mut slice[..mid], - &mut slice[mid..]) -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-05/src/main.rs:here}} ``` Listing 19-5: An attempted implementation of @@ -261,15 +227,7 @@ slice. When we try to compile the code in Listing 19-5, we’ll get an error. ```text -error[E0499]: cannot borrow `*slice` as mutable more than once at a time - --> - | -6 | (&mut slice[..mid], - | ----- first mutable borrow occurs here -7 | &mut slice[mid..]) - | ^^^^^ second mutable borrow occurs here -8 | } - | - first borrow ends here +{{#include ../listings/ch19-advanced-features/listing-19-05/output.txt}} ``` Rust’s borrow checker can’t understand that we’re borrowing different parts of @@ -282,19 +240,7 @@ Listing 19-6 shows how to use an `unsafe` block, a raw pointer, and some calls to unsafe functions to make the implementation of `split_at_mut` work. ```rust,unsafe -use std::slice; - -fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { - let len = slice.len(); - let ptr = slice.as_mut_ptr(); - - assert!(mid <= len); - - unsafe { - (slice::from_raw_parts_mut(ptr, mid), - slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid)) - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-06/src/main.rs:here}} ``` Listing 19-6: Using unsafe code in the implementation of @@ -310,16 +256,16 @@ mutable slice to `i32` values, `as_mut_ptr` returns a raw pointer with the type We keep the assertion that the `mid` index is within the slice. Then we get to the unsafe code: the `slice::from_raw_parts_mut` function takes a raw pointer and a length, and it creates a slice. We use this function to create a slice -that starts from `ptr` and is `mid` items long. Then we call the `offset` +that starts from `ptr` and is `mid` items long. Then we call the `add` method on `ptr` with `mid` as an argument to get a raw pointer that starts at `mid`, and we create a slice using that pointer and the remaining number of items after `mid` as the length. The function `slice::from_raw_parts_mut` is unsafe because it takes a raw -pointer and must trust that this pointer is valid. The `offset` method on raw +pointer and must trust that this pointer is valid. The `add` method on raw pointers is also unsafe, because it must trust that the offset location is also a valid pointer. Therefore, we had to put an `unsafe` block around our calls to -`slice::from_raw_parts_mut` and `offset` so we could call them. By looking at +`slice::from_raw_parts_mut` and `add` so we could call them. By looking at the code and by adding the assertion that `mid` must be less than or equal to `len`, we can tell that all the raw pointers used within the `unsafe` block will be valid pointers to data within the slice. This is an acceptable and @@ -336,14 +282,7 @@ likely crash when the slice is used. This code takes an arbitrary memory location and creates a slice 10,000 items long. ```rust,unsafe -use std::slice; - -let address = 0x01234usize; -let r = address as *mut i32; - -let slice: &[i32] = unsafe { - slice::from_raw_parts_mut(r, 10000) -}; +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-07/src/main.rs:here}} ``` Listing 19-7: Creating a slice from an arbitrary memory @@ -370,15 +309,7 @@ responsibility falls on the programmer to ensure safety. Filename: src/main.rs ```rust,unsafe -extern "C" { - fn abs(input: i32) -> i32; -} - -fn main() { - unsafe { - println!("Absolute value of -3 according to C: {}", abs(-3)); - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-08/src/main.rs}} ``` Listing 19-8: Declaring and calling an `extern` function @@ -428,11 +359,7 @@ value. Filename: src/main.rs ```rust -static HELLO_WORLD: &str = "Hello, world!"; - -fn main() { - println!("name is: {}", HELLO_WORLD); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-09/src/main.rs}} ``` Listing 19-9: Defining and using an immutable static @@ -461,21 +388,7 @@ static variable named `COUNTER`. Filename: src/main.rs ```rust,unsafe -static mut COUNTER: u32 = 0; - -fn add_to_count(inc: u32) { - unsafe { - COUNTER += inc; - } -} - -fn main() { - add_to_count(3); - - unsafe { - println!("COUNTER: {}", COUNTER); - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-10/src/main.rs}} ``` Listing 19-10: Reading from or writing to a mutable @@ -502,13 +415,7 @@ compiler can’t verify. We can declare that a trait is `unsafe` by adding the `unsafe` too, as shown in Listing 19-11. ```rust,unsafe -unsafe trait Foo { - // methods go here -} - -unsafe impl Foo for i32 { - // method implementations go here -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-11/src/main.rs}} ``` Listing 19-11: Defining and implementing an unsafe @@ -528,13 +435,21 @@ can’t verify that our type upholds the guarantees that it can be safely sent across threads or accessed from multiple threads; therefore, we need to do those checks manually and indicate as such with `unsafe`. +### Accessing Fields of a Union + +A `union` is similar to a `struct`, but only one declared field is used in a +particular instance at one time. Unions are primarily used to interface with +unions in C code. Accessing union fields is unsafe because Rust can’t guarantee +the type of the data currently being stored in the union instance. You can +learn more about unions in [the reference][reference]. + ### When to Use Unsafe Code -Using `unsafe` to take one of the four actions (superpowers) just discussed +Using `unsafe` to take one of the five actions (superpowers) just discussed isn’t wrong or even frowned upon. But it is trickier to get `unsafe` code correct because the compiler can’t help uphold memory safety. When you have a reason to use `unsafe` code, you can do so, and having the explicit `unsafe` -annotation makes it easier to track down the source of problems if they occur. +annotation makes it easier to track down the source of problems when they occur. [dangling-references]: ch04-02-references-and-borrowing.html#dangling-references @@ -543,3 +458,4 @@ ch03-01-variables-and-mutability.html#differences-between-variables-and-constant [extensible-concurrency-with-the-sync-and-send-traits]: ch16-04-extensible-concurrency-sync-and-send.html#extensible-concurrency-with-the-sync-and-send-traits [the-slice-type]: ch04-03-slices.html#the-slice-type +[reference]: ../reference/items/unions.html diff --git a/src/doc/book/src/ch19-03-advanced-traits.md b/src/doc/book/src/ch19-03-advanced-traits.md index c959f231dc..9c334286fd 100644 --- a/src/doc/book/src/ch19-03-advanced-traits.md +++ b/src/doc/book/src/ch19-03-advanced-traits.md @@ -28,11 +28,7 @@ Chapter 13, we mentioned that the definition of the `Iterator` trait is as shown in Listing 19-12. ```rust -pub trait Iterator { - type Item; - - fn next(&mut self) -> Option; -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-12/src/lib.rs}} ``` Listing 19-12: The definition of the `Iterator` trait @@ -54,20 +50,14 @@ Listing 13-21, we specified that the `Item` type was `u32`: Filename: src/lib.rs ```rust,ignore -impl Iterator for Counter { - type Item = u32; - - fn next(&mut self) -> Option { - // --snip-- +{{#rustdoc_include ../listings/ch19-advanced-features/listing-13-21-reproduced/src/lib.rs:ch19}} ``` This syntax seems comparable to that of generics. So why not just define the `Iterator` trait with generics, as shown in Listing 19-13? ```rust -pub trait Iterator { - fn next(&mut self) -> Option; -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-13/src/lib.rs}} ``` Listing 19-13: A hypothetical definition of the @@ -111,29 +101,7 @@ struct: Filename: src/main.rs ```rust -use std::ops::Add; - -#[derive(Debug, PartialEq)] -struct Point { - x: i32, - y: i32, -} - -impl Add for Point { - type Output = Point; - - fn add(self, other: Point) -> Point { - Point { - x: self.x + other.x, - y: self.y + other.y, - } - } -} - -fn main() { - assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, - Point { x: 3, y: 3 }); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-14/src/main.rs}} ``` Listing 19-14: Implementing the `Add` trait to overload @@ -176,18 +144,7 @@ implementation of `Add` do the conversion correctly. We can implement `Add` for Filename: src/lib.rs ```rust -use std::ops::Add; - -struct Millimeters(u32); -struct Meters(u32); - -impl Add for Millimeters { - type Output = Millimeters; - - fn add(self, other: Meters) -> Millimeters { - Millimeters(self.0 + (other.0 * 1000)) - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-15/src/lib.rs}} ``` Listing 19-15: Implementing the `Add` trait on @@ -229,33 +186,7 @@ on it. Each `fly` method does something different. Filename: src/main.rs ```rust -trait Pilot { - fn fly(&self); -} - -trait Wizard { - fn fly(&self); -} - -struct Human; - -impl Pilot for Human { - fn fly(&self) { - println!("This is your captain speaking."); - } -} - -impl Wizard for Human { - fn fly(&self) { - println!("Up!"); - } -} - -impl Human { - fn fly(&self) { - println!("*waving arms furiously*"); - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-16/src/main.rs:here}} ``` Listing 19-16: Two traits are defined to have a `fly` @@ -268,38 +199,7 @@ the method that is directly implemented on the type, as shown in Listing 19-17. Filename: src/main.rs ```rust -# trait Pilot { -# fn fly(&self); -# } -# -# trait Wizard { -# fn fly(&self); -# } -# -# struct Human; -# -# impl Pilot for Human { -# fn fly(&self) { -# println!("This is your captain speaking."); -# } -# } -# -# impl Wizard for Human { -# fn fly(&self) { -# println!("Up!"); -# } -# } -# -# impl Human { -# fn fly(&self) { -# println!("*waving arms furiously*"); -# } -# } -# -fn main() { - let person = Human; - person.fly(); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-17/src/main.rs:here}} ``` Listing 19-17: Calling `fly` on an instance of @@ -315,40 +215,7 @@ Listing 19-18 demonstrates this syntax. Filename: src/main.rs ```rust -# trait Pilot { -# fn fly(&self); -# } -# -# trait Wizard { -# fn fly(&self); -# } -# -# struct Human; -# -# impl Pilot for Human { -# fn fly(&self) { -# println!("This is your captain speaking."); -# } -# } -# -# impl Wizard for Human { -# fn fly(&self) { -# println!("Up!"); -# } -# } -# -# impl Human { -# fn fly(&self) { -# println!("*waving arms furiously*"); -# } -# } -# -fn main() { - let person = Human; - Pilot::fly(&person); - Wizard::fly(&person); - person.fly(); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-18/src/main.rs:here}} ``` Listing 19-18: Specifying which trait’s `fly` method we @@ -363,9 +230,7 @@ disambiguate. Running this code prints the following: ```text -This is your captain speaking. -Up! -*waving arms furiously* +{{#include ../listings/ch19-advanced-features/listing-19-18/output.txt}} ``` Because the `fly` method takes a `self` parameter, if we had two *types* that @@ -382,27 +247,7 @@ associated function `baby_name` defined on `Dog` directly. Filename: src/main.rs ```rust -trait Animal { - fn baby_name() -> String; -} - -struct Dog; - -impl Dog { - fn baby_name() -> String { - String::from("Spot") - } -} - -impl Animal for Dog { - fn baby_name() -> String { - String::from("puppy") - } -} - -fn main() { - println!("A baby dog is called a {}", Dog::baby_name()); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-19/src/main.rs}} ``` Listing 19-19: A trait with an associated function and a @@ -420,7 +265,7 @@ In `main`, we call the `Dog::baby_name` function, which calls the associated function defined on `Dog` directly. This code prints the following: ```text -A baby dog is called a Spot +{{#include ../listings/ch19-advanced-features/listing-19-19/output.txt}} ``` This output isn’t what we wanted. We want to call the `baby_name` function that @@ -432,9 +277,7 @@ Listing 19-20, we’ll get a compilation error. Filename: src/main.rs ```rust,ignore,does_not_compile -fn main() { - println!("A baby dog is called a {}", Animal::baby_name()); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-20/src/main.rs:here}} ``` Listing 19-20: Attempting to call the `baby_name` @@ -446,13 +289,7 @@ thus doesn’t have a `self` parameter, Rust can’t figure out which implementation of `Animal::baby_name` we want. We’ll get this compiler error: ```text -error[E0283]: type annotations required: cannot resolve `_: Animal` - --> src/main.rs:20:43 - | -20 | println!("A baby dog is called a {}", Animal::baby_name()); - | ^^^^^^^^^^^^^^^^^ - | - = note: required by `Animal::baby_name` +{{#include ../listings/ch19-advanced-features/listing-19-20/output.txt}} ``` To disambiguate and tell Rust that we want to use the implementation of @@ -462,27 +299,7 @@ demonstrates how to use fully qualified syntax. Filename: src/main.rs ```rust -# trait Animal { -# fn baby_name() -> String; -# } -# -# struct Dog; -# -# impl Dog { -# fn baby_name() -> String { -# String::from("Spot") -# } -# } -# -# impl Animal for Dog { -# fn baby_name() -> String { -# String::from("puppy") -# } -# } -# -fn main() { - println!("A baby dog is called a {}", ::baby_name()); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-21/src/main.rs:here}} ``` Listing 19-21: Using fully qualified syntax to specify @@ -495,7 +312,7 @@ implemented on `Dog` by saying that we want to treat the `Dog` type as an `Animal` for this function call. This code will now print what we want: ```text -A baby dog is called a puppy +{{#include ../listings/ch19-advanced-features/listing-19-21/output.txt}} ``` In general, fully qualified syntax is defined as follows: @@ -542,19 +359,7 @@ the trait. Listing 19-22 shows an implementation of the `OutlinePrint` trait. Filename: src/main.rs ```rust -use std::fmt; - -trait OutlinePrint: fmt::Display { - fn outline_print(&self) { - let output = self.to_string(); - let len = output.len(); - println!("{}", "*".repeat(len + 4)); - println!("*{}*", " ".repeat(len + 2)); - println!("* {} *", output); - println!("*{}*", " ".repeat(len + 2)); - println!("{}", "*".repeat(len + 4)); - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-22/src/main.rs:here}} ``` Listing 19-22: Implementing the `OutlinePrint` trait that @@ -572,27 +377,14 @@ doesn’t implement `Display`, such as the `Point` struct: Filename: src/main.rs -```rust -# trait OutlinePrint {} -struct Point { - x: i32, - y: i32, -} - -impl OutlinePrint for Point {} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/src/main.rs:here}} ``` We get an error saying that `Display` is required but not implemented: ```text -error[E0277]: the trait bound `Point: std::fmt::Display` is not satisfied - --> src/main.rs:20:6 - | -20 | impl OutlinePrint for Point {} - | ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter; -try using `:?` instead if you are using a format string - | - = help: the trait `std::fmt::Display` is not implemented for `Point` +{{#include ../listings/ch19-advanced-features/no-listing-02-impl-outlineprint-for-point/output.txt}} ``` To fix this, we implement `Display` on `Point` and satisfy the constraint that @@ -601,18 +393,7 @@ To fix this, we implement `Display` on `Point` and satisfy the constraint that Filename: src/main.rs ```rust -# struct Point { -# x: i32, -# y: i32, -# } -# -use std::fmt; - -impl fmt::Display for Point { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "({}, {})", self.x, self.y) - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-03-impl-display-for-point/src/main.rs:here}} ``` Then implementing the `OutlinePrint` trait on `Point` will compile @@ -644,20 +425,7 @@ that holds an instance of `Vec`; then we can implement `Display` on Filename: src/main.rs ```rust -use std::fmt; - -struct Wrapper(Vec); - -impl fmt::Display for Wrapper { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "[{}]", self.0.join(", ")) - } -} - -fn main() { - let w = Wrapper(vec![String::from("hello"), String::from("world")]); - println!("w = {}", w); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-23/src/main.rs}} ``` Listing 19-23: Creating a `Wrapper` type around diff --git a/src/doc/book/src/ch19-04-advanced-types.md b/src/doc/book/src/ch19-04-advanced-types.md index e1e46b1ed1..f20d6b4dae 100644 --- a/src/doc/book/src/ch19-04-advanced-types.md +++ b/src/doc/book/src/ch19-04-advanced-types.md @@ -43,7 +43,7 @@ alias* to give an existing type another name. For this we use the `type` keyword. For example, we can create the alias `Kilometers` to `i32` like so: ```rust -type Kilometers = i32; +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs:here}} ``` Now, the alias `Kilometers` is a *synonym* for `i32`; unlike the `Millimeters` @@ -52,12 +52,7 @@ new type. Values that have the type `Kilometers` will be treated the same as values of type `i32`: ```rust -type Kilometers = i32; - -let x: i32 = 5; -let y: Kilometers = 5; - -println!("x + y = {}", x + y); +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-04-kilometers-alias/src/main.rs:there}} ``` Because `Kilometers` and `i32` are the same type, we can add values of both @@ -77,16 +72,7 @@ over the code can be tiresome and error prone. Imagine having a project full of code like that in Listing 19-24. ```rust -let f: Box = Box::new(|| println!("hi")); - -fn takes_long_type(f: Box) { - // --snip-- -} - -fn returns_long_type() -> Box { - // --snip-- -# Box::new(|| ()) -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-24/src/main.rs:here}} ``` Listing 19-24: Using a long type in many places @@ -96,18 +82,7 @@ Listing 19-25, we’ve introduced an alias named `Thunk` for the verbose type an can replace all uses of the type with the shorter alias `Thunk`. ```rust -type Thunk = Box; - -let f: Thunk = Box::new(|| println!("hi")); - -fn takes_long_type(f: Thunk) { - // --snip-- -} - -fn returns_long_type() -> Thunk { - // --snip-- -# Box::new(|| ()) -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-25/src/main.rs:here}} ``` Listing 19-25: Introducing a type alias `Thunk` to reduce @@ -127,23 +102,14 @@ possible I/O errors. Many of the functions in `std::io` will be returning the `Write` trait: ```rust -use std::io::Error; -use std::fmt; - -pub trait Write { - fn write(&mut self, buf: &[u8]) -> Result; - fn flush(&mut self) -> Result<(), Error>; - - fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>; - fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>; -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-05-write-trait/src/lib.rs}} ``` The `Result<..., Error>` is repeated a lot. As such, `std::io` has this type of alias declaration: ```rust -type Result = std::result::Result; +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs:here}} ``` Because this declaration is in the `std::io` module, we can use the fully @@ -151,14 +117,8 @@ qualified alias `std::io::Result`—that is, a `Result` with the `E` filled in as `std::io::Error`. The `Write` trait function signatures end up looking like this: -```rust,ignore -pub trait Write { - fn write(&mut self, buf: &[u8]) -> Result; - fn flush(&mut self) -> Result<()>; - - fn write_all(&mut self, buf: &[u8]) -> Result<()>; - fn write_fmt(&mut self, fmt: Arguments) -> Result<()>; -} +```rust +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-06-result-alias/src/lib.rs:there}} ``` The type alias helps in two ways: it makes code easier to write *and* it gives @@ -173,10 +133,8 @@ Rust has a special type named `!` that’s known in type theory lingo as the because it stands in the place of the return type when a function will never return. Here is an example: -```rust,ignore -fn bar() -> ! { - // --snip-- -} +```rust +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-07-never-type/src/lib.rs:here}} ``` This code is read as “the function `bar` returns never.” Functions that return @@ -186,15 +144,8 @@ so `bar` can never possibly return. But what use is a type you can never create values for? Recall the code from Listing 2-5; we’ve reproduced part of it here in Listing 19-26. -```rust -# let guess = "3"; -# loop { -let guess: u32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, -}; -# break; -# } +```rust,ignore +{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-05/src/main.rs:ch19}} ``` Listing 19-26: A `match` with an arm that ends in @@ -206,10 +157,7 @@ At the time, we skipped over some details in this code. In Chapter 6 in [“The for example, the following code doesn’t work: ```rust,ignore,does_not_compile -let guess = match guess.trim().parse() { - Ok(_) => 5, - Err(_) => "hello", -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-08-match-arms-different-types/src/main.rs:here}} ``` The type of `guess` in this code would have to be an integer *and* a string, @@ -233,14 +181,7 @@ function that we call on `Option` values to produce a value or panic? Here is its definition: ```rust,ignore -impl Option { - pub fn unwrap(self) -> T { - match self { - Some(val) => val, - None => panic!("called `Option::unwrap()` on a `None` value"), - } - } -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-09-unwrap-definition/src/lib.rs:here}} ``` In this code, the same thing happens as in the `match` in Listing 19-26: Rust @@ -252,11 +193,7 @@ returning a value from `unwrap`, so this code is valid. One final expression that has the type `!` is a `loop`: ```rust,ignore -print!("forever "); - -loop { - print!("and ever "); -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-10-loop-returns-never/src/main.rs:here}} ``` Here, the loop never ends, so `!` is the value of the expression. However, this @@ -278,8 +215,7 @@ we can’t create a variable of type `str`, nor can we take an argument of type `str`. Consider the following code, which does not work: ```rust,ignore,does_not_compile -let s1: str = "Hello there!"; -let s2: str = "How's it going?"; +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-11-cant-create-str/src/main.rs:here}} ``` Rust needs to know how much memory to allocate for any value of a particular @@ -321,17 +257,13 @@ In addition, Rust implicitly adds a bound on `Sized` to every generic function. That is, a generic function definition like this: ```rust,ignore -fn generic(t: T) { - // --snip-- -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-12-generic-fn-definition/src/lib.rs}} ``` is actually treated as though we had written this: ```rust,ignore -fn generic(t: T) { - // --snip-- -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-13-generic-implicit-sized-bound/src/lib.rs}} ``` By default, generic functions will work only on types that have a known size at @@ -339,9 +271,7 @@ compile time. However, you can use the following special syntax to relax this restriction: ```rust,ignore -fn generic(t: &T) { - // --snip-- -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-14-generic-maybe-sized/src/lib.rs}} ``` A trait bound on `?Sized` is the opposite of a trait bound on `Sized`: we would diff --git a/src/doc/book/src/ch19-05-advanced-functions-and-closures.md b/src/doc/book/src/ch19-05-advanced-functions-and-closures.md index 2955114afc..ee04e8630f 100644 --- a/src/doc/book/src/ch19-05-advanced-functions-and-closures.md +++ b/src/doc/book/src/ch19-05-advanced-functions-and-closures.md @@ -1,6 +1,6 @@ ## Advanced Functions and Closures -Finally, we’ll explore some advanced features related to functions and +Next, we’ll explore some advanced features related to functions and closures, which include function pointers and returning closures. ### Function Pointers @@ -17,19 +17,7 @@ similar to that of closures, as shown in Listing 19-27. Filename: src/main.rs ```rust -fn add_one(x: i32) -> i32 { - x + 1 -} - -fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { - f(arg) + f(arg) -} - -fn main() { - let answer = do_twice(add_one, 5); - - println!("The answer is: {}", answer); -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-27/src/main.rs}} ``` Listing 19-27: Using the `fn` type to accept a function @@ -59,22 +47,14 @@ function, let’s look at a use of `map`. To use the `map` function to turn a vector of numbers into a vector of strings, we could use a closure, like this: ```rust -let list_of_numbers = vec![1, 2, 3]; -let list_of_strings: Vec = list_of_numbers - .iter() - .map(|i| i.to_string()) - .collect(); +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-15-map-closure/src/main.rs:here}} ``` Or we could name a function as the argument to `map` instead of the closure, like this: ```rust -let list_of_numbers = vec![1, 2, 3]; -let list_of_strings: Vec = list_of_numbers - .iter() - .map(ToString::to_string) - .collect(); +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-16-map-function/src/main.rs:here}} ``` Note that we must use the fully qualified syntax that we talked about earlier @@ -92,15 +72,7 @@ implement the closure traits, which means we can specify the initializer functions as arguments for methods that take closures, like so: ```rust -enum Status { - Value(u32), - Stop, -} - -let list_of_statuses: Vec = - (0u32..20) - .map(Status::Value) - .collect(); +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-17-map-initializer/src/main.rs:here}} ``` Here we create `Status::Value` instances using each `u32` value in the range @@ -120,25 +92,13 @@ pointer `fn` as a return type, for example. The following code tries to return a closure directly, but it won’t compile: ```rust,ignore,does_not_compile -fn returns_closure() -> Fn(i32) -> i32 { - |x| x + 1 -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-18-returns-closure/src/lib.rs}} ``` The compiler error is as follows: ```text -error[E0277]: the trait bound `std::ops::Fn(i32) -> i32 + 'static: -std::marker::Sized` is not satisfied - --> - | -1 | fn returns_closure() -> Fn(i32) -> i32 { - | ^^^^^^^^^^^^^^ `std::ops::Fn(i32) -> i32 + 'static` - does not have a constant size known at compile-time - | - = help: the trait `std::marker::Sized` is not implemented for - `std::ops::Fn(i32) -> i32 + 'static` - = note: the return type of a function must have a statically known size +{{#include ../listings/ch19-advanced-features/no-listing-18-returns-closure/output.txt}} ``` The error references the `Sized` trait again! Rust doesn’t know how much space @@ -146,9 +106,7 @@ it will need to store the closure. We saw a solution to this problem earlier. We can use a trait object: ```rust -fn returns_closure() -> Box i32> { - Box::new(|x| x + 1) -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-19-returns-closure-trait-object/src/lib.rs}} ``` This code will compile just fine. For more about trait objects, refer to the diff --git a/src/doc/book/src/ch19-06-macros.md b/src/doc/book/src/ch19-06-macros.md index fbb2246934..8733ee7f72 100644 --- a/src/doc/book/src/ch19-06-macros.md +++ b/src/doc/book/src/ch19-06-macros.md @@ -78,18 +78,7 @@ Listing 19-28 shows a slightly simplified definition of the `vec!` macro. Filename: src/lib.rs ```rust -#[macro_export] -macro_rules! vec { - ( $( $x:expr ),* ) => { - { - let mut temp_vec = Vec::new(); - $( - temp_vec.push($x); - )* - temp_vec - } - }; -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-28/src/lib.rs}} ``` Listing 19-28: A simplified version of the `vec!` macro @@ -120,7 +109,7 @@ covered in Chapter 18 because macro patterns are matched against Rust code structure rather than values. Let’s walk through what the pattern pieces in Listing 19-28 mean; for the full macro pattern syntax, see [the reference]. -[the reference]: ../reference/macros.html +[the reference]: ../reference/macros-by-example.html First, a set of parentheses encompasses the whole pattern. A dollar sign (`$`) is next, followed by a set of parentheses that captures values that match the @@ -143,11 +132,13 @@ macro with `vec![1, 2, 3];`, the code generated that replaces this macro call will be the following: ```rust,ignore -let mut temp_vec = Vec::new(); -temp_vec.push(1); -temp_vec.push(2); -temp_vec.push(3); -temp_vec +{ + let mut temp_vec = Vec::new(); + temp_vec.push(1); + temp_vec.push(2); + temp_vec.push(3); + temp_vec +} ``` We’ve defined a macro that can take any number of arguments of any type and can @@ -221,16 +212,8 @@ programmer to write code like Listing 19-30 using our crate. Filename: src/main.rs -```rust,ignore -use hello_macro::HelloMacro; -use hello_macro_derive::HelloMacro; - -#[derive(HelloMacro)] -struct Pancakes; - -fn main() { - Pancakes::hello_macro(); -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-30/src/main.rs}} ``` Listing 19-30: The code a user of our crate will be able @@ -248,28 +231,14 @@ Next, we’ll define the `HelloMacro` trait and its associated function: Filename: src/lib.rs ```rust -pub trait HelloMacro { - fn hello_macro(); -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/hello_macro/src/lib.rs}} ``` We have a trait and its function. At this point, our crate user could implement the trait to achieve the desired functionality, like so: ```rust,ignore -use hello_macro::HelloMacro; - -struct Pancakes; - -impl HelloMacro for Pancakes { - fn hello_macro() { - println!("Hello, Macro! My name is Pancakes!"); - } -} - -fn main() { - Pancakes::hello_macro(); -} +{{#rustdoc_include ../listings/ch19-advanced-features/no-listing-20-impl-hellomacro-for-pancakes/pancakes/src/main.rs}} ``` However, they would need to write the implementation block for each type they @@ -311,12 +280,7 @@ in a moment, so we need to add them as dependencies. Add the following to the Filename: hello_macro_derive/Cargo.toml ```toml -[lib] -proc-macro = true - -[dependencies] -syn = "0.14.4" -quote = "0.6.3" +{{#include ../listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/Cargo.toml:7:12}} ``` To start defining the procedural macro, place the code in Listing 19-31 into @@ -325,29 +289,8 @@ won’t compile until we add a definition for the `impl_hello_macro` function. Filename: hello_macro_derive/src/lib.rs - - -```rust,ignore -extern crate proc_macro; - -use crate::proc_macro::TokenStream; -use quote::quote; -use syn; - -#[proc_macro_derive(HelloMacro)] -pub fn hello_macro_derive(input: TokenStream) -> TokenStream { - // Construct a representation of Rust code as a syntax tree - // that we can manipulate - let ast = syn::parse(input).unwrap(); - - // Build the trait implementation - impl_hello_macro(&ast) -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-31/hello_macro/hello_macro_derive/src/lib.rs}} ``` Listing 19-31: Code that most procedural macro crates @@ -417,7 +360,7 @@ with the `ident` (identifier, meaning the name) of `Pancakes`. There are more fields on this struct for describing all sorts of Rust code; check the [`syn` documentation for `DeriveInput`][syn-docs] for more information. -[syn-docs]: https://docs.rs/syn/0.14.4/syn/struct.DeriveInput.html +[syn-docs]: https://docs.rs/syn/1.0/syn/struct.DeriveInput.html Soon we’ll define the `impl_hello_macro` function, which is where we’ll build the new Rust code we want to include. But before we do, note that the output @@ -441,17 +384,7 @@ into a `DeriveInput` instance, let’s generate the code that implements the Filename: hello_macro_derive/src/lib.rs ```rust,ignore -fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { - let name = &ast.ident; - let gen = quote! { - impl HelloMacro for #name { - fn hello_macro() { - println!("Hello, Macro! My name is {}", stringify!(#name)); - } - } - }; - gen.into() -} +{{#rustdoc_include ../listings/ch19-advanced-features/listing-19-33/hello_macro/hello_macro_derive/src/lib.rs:here}} ``` Listing 19-33: Implementing the `HelloMacro` trait using @@ -502,9 +435,7 @@ crate’s *Cargo.toml*. If you’re publishing your versions of `hello_macro` an dependencies; if not, you can specify them as `path` dependencies as follows: ```toml -[dependencies] -hello_macro = { path = "../hello_macro" } -hello_macro_derive = { path = "../hello_macro/hello_macro_derive" } +{{#include ../listings/ch19-advanced-features/no-listing-21-pancakes/pancakes/Cargo.toml:7:9}} ``` Put the code in Listing 19-30 into *src/main.rs*, and run `cargo run`: it diff --git a/src/doc/book/src/ch20-01-single-threaded.md b/src/doc/book/src/ch20-01-single-threaded.md index a2617c00a0..b46d39f656 100644 --- a/src/doc/book/src/ch20-01-single-threaded.md +++ b/src/doc/book/src/ch20-01-single-threaded.md @@ -38,17 +38,7 @@ an incoming stream, it will print `Connection established!`. Filename: src/main.rs ```rust,no_run -use std::net::TcpListener; - -fn main() { - let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); - - for stream in listener.incoming() { - let stream = stream.unwrap(); - - println!("Connection established!"); - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-01/src/main.rs}} ``` Listing 20-1: Listening for incoming streams and printing @@ -140,27 +130,7 @@ look like Listing 20-2. Filename: src/main.rs ```rust,no_run -use std::io::prelude::*; -use std::net::TcpStream; -use std::net::TcpListener; - -fn main() { - let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); - - for stream in listener.incoming() { - let stream = stream.unwrap(); - - handle_connection(stream); - } -} - -fn handle_connection(mut stream: TcpStream) { - let mut buffer = [0; 512]; - - stream.read(&mut buffer).unwrap(); - - println!("Request: {}", String::from_utf8_lossy(&buffer[..])); -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-02/src/main.rs}} ``` Listing 20-2: Reading from the `TcpStream` and printing @@ -200,7 +170,7 @@ program’s output in the terminal will now look similar to this: ```text $ cargo run Compiling hello v0.1.0 (file:///projects/hello) - Finished dev [unoptimized + debuginfo] target(s) in 0.42 secs + Finished dev [unoptimized + debuginfo] target(s) in 0.42s Running `target/debug/hello` Request: GET / HTTP/1.1 Host: 127.0.0.1:7878 @@ -295,19 +265,8 @@ Listing 20-3. Filename: src/main.rs -```rust -# use std::io::prelude::*; -# use std::net::TcpStream; -fn handle_connection(mut stream: TcpStream) { - let mut buffer = [0; 512]; - - stream.read(&mut buffer).unwrap(); - - let response = "HTTP/1.1 200 OK\r\n\r\n"; - - stream.write(response.as_bytes()).unwrap(); - stream.flush().unwrap(); -} +```rust,no_run +{{#rustdoc_include ../listings/ch20-web-server/listing-20-03/src/main.rs:here}} ``` Listing 20-3: Writing a tiny successful HTTP response to @@ -340,17 +299,7 @@ possibility. Filename: hello.html ```html - - - - - Hello! - - -

Hello!

-

Hi from Rust

- - +{{#include ../listings/ch20-web-server/listing-20-04/hello.html}} ``` Listing 20-4: A sample HTML file to return in a @@ -363,23 +312,8 @@ and send it. Filename: src/main.rs -```rust -# use std::io::prelude::*; -# use std::net::TcpStream; -use std::fs; -// --snip-- - -fn handle_connection(mut stream: TcpStream) { - let mut buffer = [0; 512]; - stream.read(&mut buffer).unwrap(); - - let contents = fs::read_to_string("hello.html").unwrap(); - - let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); - - stream.write(response.as_bytes()).unwrap(); - stream.flush().unwrap(); -} +```rust,no_run +{{#rustdoc_include ../listings/ch20-web-server/listing-20-05/src/main.rs:here}} ``` Listing 20-5: Sending the contents of *hello.html* as the @@ -415,29 +349,8 @@ received against what we know a request for */* looks like and adds `if` and Filename: src/main.rs -```rust -# use std::io::prelude::*; -# use std::net::TcpStream; -# use std::fs; -// --snip-- - -fn handle_connection(mut stream: TcpStream) { - let mut buffer = [0; 512]; - stream.read(&mut buffer).unwrap(); - - let get = b"GET / HTTP/1.1\r\n"; - - if buffer.starts_with(get) { - let contents = fs::read_to_string("hello.html").unwrap(); - - let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); - - stream.write(response.as_bytes()).unwrap(); - stream.flush().unwrap(); - } else { - // some other request - } -} +```rust,no_run +{{#rustdoc_include ../listings/ch20-web-server/listing-20-06/src/main.rs:here}} ``` Listing 20-6: Matching the request and handling requests @@ -467,24 +380,8 @@ indicating the response to the end user. Filename: src/main.rs -```rust -# use std::io::prelude::*; -# use std::net::TcpStream; -# use std::fs; -# fn handle_connection(mut stream: TcpStream) { -# if true { -// --snip-- - -} else { - let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n"; - let contents = fs::read_to_string("404.html").unwrap(); - - let response = format!("{}{}", status_line, contents); - - stream.write(response.as_bytes()).unwrap(); - stream.flush().unwrap(); -} -# } +```rust,no_run +{{#rustdoc_include ../listings/ch20-web-server/listing-20-07/src/main.rs:here}} ``` Listing 20-7: Responding with status code 404 and an @@ -499,17 +396,7 @@ any HTML you want or use the example HTML in Listing 20-8. Filename: 404.html ```html - - - - - Hello! - - -

Oops!

-

Sorry, I don't know what you're asking for.

- - +{{#include ../listings/ch20-web-server/listing-20-08/404.html}} ``` Listing 20-8: Sample content for the page to send back @@ -532,32 +419,8 @@ the large `if` and `else` blocks. Filename: src/main.rs -```rust -# use std::io::prelude::*; -# use std::net::TcpStream; -# use std::fs; -// --snip-- - -fn handle_connection(mut stream: TcpStream) { -# let mut buffer = [0; 512]; -# stream.read(&mut buffer).unwrap(); -# -# let get = b"GET / HTTP/1.1\r\n"; - // --snip-- - - let (status_line, filename) = if buffer.starts_with(get) { - ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") - } else { - ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") - }; - - let contents = fs::read_to_string(filename).unwrap(); - - let response = format!("{}{}", status_line, contents); - - stream.write(response.as_bytes()).unwrap(); - stream.flush().unwrap(); -} +```rust,no_run +{{#rustdoc_include ../listings/ch20-web-server/listing-20-09/src/main.rs:here}} ``` Listing 20-9: Refactoring the `if` and `else` blocks to diff --git a/src/doc/book/src/ch20-02-multithreaded.md b/src/doc/book/src/ch20-02-multithreaded.md index 40d3a172c8..c0731d214c 100644 --- a/src/doc/book/src/ch20-02-multithreaded.md +++ b/src/doc/book/src/ch20-02-multithreaded.md @@ -17,33 +17,8 @@ for 5 seconds before responding. Filename: src/main.rs -```rust -use std::thread; -use std::time::Duration; -# use std::io::prelude::*; -# use std::net::TcpStream; -# use std::fs::File; -// --snip-- - -fn handle_connection(mut stream: TcpStream) { -# let mut buffer = [0; 512]; -# stream.read(&mut buffer).unwrap(); - // --snip-- - - let get = b"GET / HTTP/1.1\r\n"; - let sleep = b"GET /sleep HTTP/1.1\r\n"; - - let (status_line, filename) = if buffer.starts_with(get) { - ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") - } else if buffer.starts_with(sleep) { - thread::sleep(Duration::from_secs(5)); - ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") - } else { - ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") - }; - - // --snip-- -} +```rust,no_run +{{#rustdoc_include ../listings/ch20-web-server/listing-20-10/src/main.rs:here}} ``` Listing 20-10: Simulating a slow request by recognizing @@ -124,23 +99,7 @@ new thread to handle each stream within the `for` loop. Filename: src/main.rs ```rust,no_run -# use std::thread; -# use std::io::prelude::*; -# use std::net::TcpListener; -# use std::net::TcpStream; -# -fn main() { - let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); - - for stream in listener.incoming() { - let stream = stream.unwrap(); - - thread::spawn(|| { - handle_connection(stream); - }); - } -} -# fn handle_connection(mut stream: TcpStream) {} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-11/src/main.rs:here}} ``` Listing 20-11: Spawning a new thread for each @@ -162,31 +121,8 @@ struct we want to use instead of `thread::spawn`. Filename: src/main.rs -```rust,no_run -# use std::thread; -# use std::io::prelude::*; -# use std::net::TcpListener; -# use std::net::TcpStream; -# struct ThreadPool; -# impl ThreadPool { -# fn new(size: u32) -> ThreadPool { ThreadPool } -# fn execute(&self, f: F) -# where F: FnOnce() + Send + 'static {} -# } -# -fn main() { - let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); - let pool = ThreadPool::new(4); - - for stream in listener.incoming() { - let stream = stream.unwrap(); - - pool.execute(|| { - handle_connection(stream); - }); - } -} -# fn handle_connection(mut stream: TcpStream) {} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch20-web-server/listing-20-12/src/main.rs:here}} ``` Listing 20-12: Our ideal `ThreadPool` interface @@ -205,16 +141,7 @@ compiler errors from `cargo check` to drive our development. Here is the first error we get: ```text -$ cargo check - Compiling hello v0.1.0 (file:///projects/hello) -error[E0433]: failed to resolve. Use of undeclared type or module `ThreadPool` - --> src\main.rs:10:16 - | -10 | let pool = ThreadPool::new(4); - | ^^^^^^^^^^^^^^^ Use of undeclared type or module - `ThreadPool` - -error: aborting due to previous error +{{#include ../listings/ch20-web-server/listing-20-12/output.txt}} ``` Great! This error tells us we need a `ThreadPool` type or module, so we’ll @@ -231,7 +158,7 @@ definition of a `ThreadPool` struct that we can have for now: Filename: src/lib.rs ```rust -pub struct ThreadPool; +{{#rustdoc_include ../listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/lib.rs}} ``` Then create a new directory, *src/bin*, and move the binary crate rooted in @@ -244,22 +171,14 @@ following code to the top of *src/bin/main.rs*: Filename: src/bin/main.rs ```rust,ignore -use hello::ThreadPool; +{{#rustdoc_include ../listings/ch20-web-server/no-listing-01-define-threadpool-struct/src/bin/main.rs:here}} ``` This code still won’t work, but let’s check it again to get the next error that we need to address: ```text -$ cargo check - Compiling hello v0.1.0 (file:///projects/hello) -error[E0599]: no function or associated item named `new` found for type -`hello::ThreadPool` in the current scope - --> src/bin/main.rs:13:16 - | -13 | let pool = ThreadPool::new(4); - | ^^^^^^^^^^^^^^^ function or associated item not found in - `hello::ThreadPool` +{{#include ../listings/ch20-web-server/no-listing-01-define-threadpool-struct/output.txt}} ``` This error indicates that next we need to create an associated function named @@ -271,13 +190,7 @@ characteristics: Filename: src/lib.rs ```rust -pub struct ThreadPool; - -impl ThreadPool { - pub fn new(size: usize) -> ThreadPool { - ThreadPool - } -} +{{#rustdoc_include ../listings/ch20-web-server/no-listing-02-impl-threadpool-new/src/lib.rs:here}} ``` We chose `usize` as the type of the `size` parameter, because we know that a @@ -289,27 +202,11 @@ ignore --> section of Chapter 3. Let’s check the code again: ```text -$ cargo check - Compiling hello v0.1.0 (file:///projects/hello) -warning: unused variable: `size` - --> src/lib.rs:4:16 - | -4 | pub fn new(size: usize) -> ThreadPool { - | ^^^^ - | - = note: #[warn(unused_variables)] on by default - = note: to avoid this warning, consider using `_size` instead - -error[E0599]: no method named `execute` found for type `hello::ThreadPool` in the current scope - --> src/bin/main.rs:18:14 - | -18 | pool.execute(|| { - | ^^^^^^^ +{{#include ../listings/ch20-web-server/no-listing-02-impl-threadpool-new/output.txt}} ``` -Now we get a warning and an error. Ignoring the warning for a moment, the error -occurs because we don’t have an `execute` method on `ThreadPool`. Recall from -the [“Creating a Similar Interface for a Finite Number of +Now the error occurs because we don’t have an `execute` method on `ThreadPool`. +Recall from the [“Creating a Similar Interface for a Finite Number of Threads”](#creating-a-similar-interface-for-a-finite-number-of-threads) section that we decided our thread pool should have an interface similar to `thread::spawn`. In addition, we’ll implement the `execute` function @@ -350,17 +247,7 @@ the thread will take to execute. Let’s create an `execute` method on Filename: src/lib.rs ```rust -# pub struct ThreadPool; -impl ThreadPool { - // --snip-- - - pub fn execute(&self, f: F) - where - F: FnOnce() + Send + 'static - { - - } -} +{{#rustdoc_include ../listings/ch20-web-server/no-listing-03-define-execute/src/lib.rs:here}} ``` We still use the `()` after `FnOnce` because this `FnOnce` represents a closure @@ -372,30 +259,13 @@ Again, this is the simplest implementation of the `execute` method: it does nothing, but we’re trying only to make our code compile. Let’s check it again: ```text -$ cargo check - Compiling hello v0.1.0 (file:///projects/hello) -warning: unused variable: `size` - --> src/lib.rs:4:16 - | -4 | pub fn new(size: usize) -> ThreadPool { - | ^^^^ - | - = note: #[warn(unused_variables)] on by default - = note: to avoid this warning, consider using `_size` instead - -warning: unused variable: `f` - --> src/lib.rs:8:30 - | -8 | pub fn execute(&self, f: F) - | ^ - | - = note: to avoid this warning, consider using `_f` instead +{{#include ../listings/ch20-web-server/no-listing-03-define-execute/output.txt}} ``` -We’re receiving only warnings now, which means it compiles! But note that if -you try `cargo run` and make a request in the browser, you’ll see the errors in -the browser that we saw at the beginning of the chapter. Our library isn’t -actually calling the closure passed to `execute` yet! +It compiles! But note that if you try `cargo run` and make a request in the +browser, you’ll see the errors in the browser that we saw at the beginning of +the chapter. Our library isn’t actually calling the closure passed to `execute` +yet! > Note: A saying you might hear about languages with strict compilers, such as > Haskell and Rust, is “if the code compiles, it works.” But this saying is not @@ -406,36 +276,19 @@ actually calling the closure passed to `execute` yet! #### Validating the Number of Threads in `new` -We’ll continue to get warnings because we aren’t doing anything with the -parameters to `new` and `execute`. Let’s implement the bodies of these -functions with the behavior we want. To start, let’s think about `new`. Earlier -we chose an unsigned type for the `size` parameter, because a pool with a -negative number of threads makes no sense. However, a pool with zero threads -also makes no sense, yet zero is a perfectly valid `usize`. We’ll add code to -check that `size` is greater than zero before we return a `ThreadPool` instance -and have the program panic if it receives a zero by using the `assert!` macro, -as shown in Listing 20-13. +We aren’t doing anything with the parameters to `new` and `execute`. Let’s +implement the bodies of these functions with the behavior we want. To start, +let’s think about `new`. Earlier we chose an unsigned type for the `size` +parameter, because a pool with a negative number of threads makes no sense. +However, a pool with zero threads also makes no sense, yet zero is a perfectly +valid `usize`. We’ll add code to check that `size` is greater than zero before +we return a `ThreadPool` instance and have the program panic if it receives a +zero by using the `assert!` macro, as shown in Listing 20-13. Filename: src/lib.rs ```rust -# pub struct ThreadPool; -impl ThreadPool { - /// Create a new ThreadPool. - /// - /// The size is the number of threads in the pool. - /// - /// # Panics - /// - /// The `new` function will panic if the size is zero. - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - ThreadPool - } - - // --snip-- -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-13/src/lib.rs:here}} ``` Listing 20-13: Implementing `ThreadPool::new` to panic if @@ -486,30 +339,7 @@ returned a `ThreadPool` instance containing them. Filename: src/lib.rs ```rust,ignore,not_desired_behavior -use std::thread; - -pub struct ThreadPool { - threads: Vec>, -} - -impl ThreadPool { - // --snip-- - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - let mut threads = Vec::with_capacity(size); - - for _ in 0..size { - // create some threads and store them in the vector - } - - ThreadPool { - threads - } - } - - // --snip-- -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-14/src/lib.rs:here}} ``` Listing 20-14: Creating a vector for `ThreadPool` to hold @@ -575,45 +405,7 @@ Ready? Here is Listing 20-15 with one way to make the preceding modifications. Filename: src/lib.rs ```rust -use std::thread; - -pub struct ThreadPool { - workers: Vec, -} - -impl ThreadPool { - // --snip-- - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - let mut workers = Vec::with_capacity(size); - - for id in 0..size { - workers.push(Worker::new(id)); - } - - ThreadPool { - workers - } - } - // --snip-- -} - -struct Worker { - id: usize, - thread: thread::JoinHandle<()>, -} - -impl Worker { - fn new(id: usize) -> Worker { - let thread = thread::spawn(|| {}); - - Worker { - id, - thread, - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-15/src/lib.rs:here}} ``` Listing 20-15: Modifying `ThreadPool` to hold `Worker` @@ -668,53 +460,7 @@ the channel. Filename: src/lib.rs ```rust -# use std::thread; -// --snip-- -use std::sync::mpsc; - -pub struct ThreadPool { - workers: Vec, - sender: mpsc::Sender, -} - -struct Job; - -impl ThreadPool { - // --snip-- - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - let (sender, receiver) = mpsc::channel(); - - let mut workers = Vec::with_capacity(size); - - for id in 0..size { - workers.push(Worker::new(id)); - } - - ThreadPool { - workers, - sender, - } - } - // --snip-- -} -# -# struct Worker { -# id: usize, -# thread: thread::JoinHandle<()>, -# } -# -# impl Worker { -# fn new(id: usize) -> Worker { -# let thread = thread::spawn(|| {}); -# -# Worker { -# id, -# thread, -# } -# } -# } +{{#rustdoc_include ../listings/ch20-web-server/listing-20-16/src/lib.rs:here}} ``` Listing 20-16: Modifying `ThreadPool` to store the @@ -731,41 +477,7 @@ the closure. The code in Listing 20-17 won’t quite compile yet. Filename: src/lib.rs ```rust,ignore,does_not_compile -impl ThreadPool { - // --snip-- - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - let (sender, receiver) = mpsc::channel(); - - let mut workers = Vec::with_capacity(size); - - for id in 0..size { - workers.push(Worker::new(id, receiver)); - } - - ThreadPool { - workers, - sender, - } - } - // --snip-- -} - -// --snip-- - -impl Worker { - fn new(id: usize, receiver: mpsc::Receiver) -> Worker { - let thread = thread::spawn(|| { - receiver; - }); - - Worker { - id, - thread, - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-17/src/lib.rs:here}} ``` Listing 20-17: Passing the receiving end of the channel @@ -777,17 +489,7 @@ the channel into `Worker::new`, and then we use it inside the closure. When we try to check this code, we get this error: ```text -$ cargo check - Compiling hello v0.1.0 (file:///projects/hello) -error[E0382]: use of moved value: `receiver` - --> src/lib.rs:27:42 - | -27 | workers.push(Worker::new(id, receiver)); - | ^^^^^^^^ value moved here in - previous iteration of loop - | - = note: move occurs because `receiver` has type - `std::sync::mpsc::Receiver`, which does not implement the `Copy` trait +{{#include ../listings/ch20-web-server/listing-20-17/output.txt}} ``` The code is trying to pass `receiver` to multiple `Worker` instances. This @@ -810,60 +512,7 @@ receiver at a time. Listing 20-18 shows the changes we need to make. Filename: src/lib.rs ```rust -# use std::thread; -# use std::sync::mpsc; -use std::sync::Arc; -use std::sync::Mutex; -// --snip-- - -# pub struct ThreadPool { -# workers: Vec, -# sender: mpsc::Sender, -# } -# struct Job; -# -impl ThreadPool { - // --snip-- - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - let (sender, receiver) = mpsc::channel(); - - let receiver = Arc::new(Mutex::new(receiver)); - - let mut workers = Vec::with_capacity(size); - - for id in 0..size { - workers.push(Worker::new(id, Arc::clone(&receiver))); - } - - ThreadPool { - workers, - sender, - } - } - - // --snip-- -} - -# struct Worker { -# id: usize, -# thread: thread::JoinHandle<()>, -# } -# -impl Worker { - fn new(id: usize, receiver: Arc>>) -> Worker { - // --snip-- -# let thread = thread::spawn(|| { -# receiver; -# }); -# -# Worker { -# id, -# thread, -# } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-18/src/lib.rs:here}} ``` Listing 20-18: Sharing the receiving end of the channel @@ -887,30 +536,7 @@ at Listing 20-19. Filename: src/lib.rs ```rust -// --snip-- -# pub struct ThreadPool { -# workers: Vec, -# sender: mpsc::Sender, -# } -# use std::sync::mpsc; -# struct Worker {} - -type Job = Box; - -impl ThreadPool { - // --snip-- - - pub fn execute(&self, f: F) - where - F: FnOnce() + Send + 'static - { - let job = Box::new(f); - - self.sender.send(job).unwrap(); - } -} - -// --snip-- +{{#rustdoc_include ../listings/ch20-web-server/listing-20-19/src/lib.rs:here}} ``` Listing 20-19: Creating a `Job` type alias for a `Box` @@ -933,27 +559,8 @@ shown in Listing 20-20 to `Worker::new`. Filename: src/lib.rs -```rust,ignore,does_not_compile -// --snip-- - -impl Worker { - fn new(id: usize, receiver: Arc>>) -> Worker { - let thread = thread::spawn(move || { - loop { - let job = receiver.lock().unwrap().recv().unwrap(); - - println!("Worker {} got a job; executing.", id); - - job(); - } - }); - - Worker { - id, - thread, - } - } -} +```rust +{{#rustdoc_include ../listings/ch20-web-server/listing-20-20/src/lib.rs:here}} ``` Listing 20-20: Receiving and executing the jobs in the @@ -976,39 +583,41 @@ The call to `recv` blocks, so if there is no job yet, the current thread will wait until a job becomes available. The `Mutex` ensures that only one `Worker` thread at a time is trying to request a job. - With the implementation of this trick, our thread pool is in a working state! Give it a `cargo run` and make some requests: + + ```text $ cargo run Compiling hello v0.1.0 (file:///projects/hello) -warning: field is never used: `workers` +warning: field is never read: `workers` --> src/lib.rs:7:5 | 7 | workers: Vec, | ^^^^^^^^^^^^^^^^^^^^ | - = note: #[warn(dead_code)] on by default + = note: `#[warn(dead_code)]` on by default -warning: field is never used: `id` - --> src/lib.rs:61:5 +warning: field is never read: `id` + --> src/lib.rs:48:5 | -61 | id: usize, +48 | id: usize, | ^^^^^^^^^ - | - = note: #[warn(dead_code)] on by default -warning: field is never used: `thread` - --> src/lib.rs:62:5 +warning: field is never read: `thread` + --> src/lib.rs:49:5 | -62 | thread: thread::JoinHandle<()>, +49 | thread: thread::JoinHandle<()>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: #[warn(dead_code)] on by default - Finished dev [unoptimized + debuginfo] target(s) in 0.99 secs - Running `target/debug/hello` + Finished dev [unoptimized + debuginfo] target(s) in 1.40s + Running `target/debug/main` Worker 0 got a job; executing. Worker 2 got a job; executing. Worker 1 got a job; executing. @@ -1038,24 +647,7 @@ why we didn’t write the worker thread code as shown in Listing 20-21. Filename: src/lib.rs ```rust,ignore,not_desired_behavior -// --snip-- - -impl Worker { - fn new(id: usize, receiver: Arc>>) -> Worker { - let thread = thread::spawn(move || { - while let Ok(job) = receiver.lock().unwrap().recv() { - println!("Worker {} got a job; executing.", id); - - job(); - } - }); - - Worker { - id, - thread, - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-21/src/lib.rs:here}} ``` Listing 20-21: An alternative implementation of @@ -1070,15 +662,15 @@ method returns. At compile time, the borrow checker can then enforce the rule that a resource guarded by a `Mutex` cannot be accessed unless we hold the lock. But this implementation can also result in the lock being held longer than intended if we don’t think carefully about the lifetime of the -`MutexGuard`. Because the values in the `while` expression remain in scope -for the duration of the block, the lock remains held for the duration of the -call to `job()`, meaning other workers cannot receive jobs. - -By using `loop` instead and acquiring the lock and a job within the block -rather than outside it, the `MutexGuard` returned from the `lock` method is -dropped as soon as the `let job` statement ends. This ensures that the lock is -held during the call to `recv`, but it is released before the call to -`job()`, allowing multiple requests to be serviced concurrently. +`MutexGuard`. Because the values in the `while let` expression remain in +scope for the duration of the block, the lock remains held for the duration of +the call to `job()`, meaning other workers cannot receive jobs. + +By using `loop` instead and acquiring the lock without assigning to a variable, +the temporary `MutexGuard` returned from the `lock` method is dropped as soon +as the `let job` statement ends. This ensures that the lock is held during the +call to `recv`, but it is released before the call to `job()`, allowing +multiple requests to be serviced concurrently. [creating-type-synonyms-with-type-aliases]: ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases diff --git a/src/doc/book/src/ch20-03-graceful-shutdown-and-cleanup.md b/src/doc/book/src/ch20-03-graceful-shutdown-and-cleanup.md index 174378b935..13df0492a4 100644 --- a/src/doc/book/src/ch20-03-graceful-shutdown-and-cleanup.md +++ b/src/doc/book/src/ch20-03-graceful-shutdown-and-cleanup.md @@ -24,15 +24,7 @@ quite work yet. Filename: src/lib.rs ```rust,ignore,does_not_compile -impl Drop for ThreadPool { - fn drop(&mut self) { - for worker in &mut self.workers { - println!("Shutting down worker {}", worker.id); - - worker.thread.join().unwrap(); - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-22/src/lib.rs:here}} ``` Listing 20-22: Joining each thread when the thread pool @@ -48,11 +40,7 @@ into an ungraceful shutdown. Here is the error we get when we compile this code: ```text -error[E0507]: cannot move out of borrowed content - --> src/lib.rs:65:13 - | -65 | worker.thread.join().unwrap(); - | ^^^^^^ cannot move out of borrowed content +{{#include ../listings/ch20-web-server/listing-20-22/output.txt}} ``` The error tells us we can’t call `join` because we only have a mutable borrow @@ -70,37 +58,15 @@ So we know we want to update the definition of `Worker` like this: Filename: src/lib.rs -```rust -# use std::thread; -struct Worker { - id: usize, - thread: Option>, -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs:here}} ``` Now let’s lean on the compiler to find the other places that need to change. Checking this code, we get two errors: ```text -error[E0599]: no method named `join` found for type -`std::option::Option>` in the current scope - --> src/lib.rs:65:27 - | -65 | worker.thread.join().unwrap(); - | ^^^^ - -error[E0308]: mismatched types - --> src/lib.rs:89:13 - | -89 | thread, - | ^^^^^^ - | | - | expected enum `std::option::Option`, found struct - `std::thread::JoinHandle` - | help: try using a variant of the expected type: `Some(thread)` - | - = note: expected type `std::option::Option>` - found type `std::thread::JoinHandle<_>` +{{#include ../listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt}} ``` Let’s address the second error, which points to the code at the end of @@ -110,16 +76,7 @@ new `Worker`. Make the following changes to fix this error: Filename: src/lib.rs ```rust,ignore -impl Worker { - fn new(id: usize, receiver: Arc>>) -> Worker { - // --snip-- - - Worker { - id, - thread: Some(thread), - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs:here}} ``` The first error is in our `Drop` implementation. We mentioned earlier that we @@ -129,17 +86,7 @@ The following changes will do so: Filename: src/lib.rs ```rust,ignore -impl Drop for ThreadPool { - fn drop(&mut self) { - for worker in &mut self.workers { - println!("Shutting down worker {}", worker.id); - - if let Some(thread) = worker.thread.take() { - thread.join().unwrap(); - } - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs:here}} ``` As discussed in Chapter 17, the `take` method on `Option` takes the `Some` @@ -166,11 +113,7 @@ variants. Filename: src/lib.rs ```rust -# struct Job; -enum Message { - NewJob(Job), - Terminate, -} +{{#rustdoc_include ../listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs:here}} ``` This `Message` enum will either be a `NewJob` variant that holds the `Job` the @@ -183,57 +126,7 @@ We need to adjust the channel to use values of type `Message` rather than type Filename: src/lib.rs ```rust,ignore -pub struct ThreadPool { - workers: Vec, - sender: mpsc::Sender, -} - -// --snip-- - -impl ThreadPool { - // --snip-- - - pub fn execute(&self, f: F) - where - F: FnOnce() + Send + 'static - { - let job = Box::new(f); - - self.sender.send(Message::NewJob(job)).unwrap(); - } -} - -// --snip-- - -impl Worker { - fn new(id: usize, receiver: Arc>>) -> - Worker { - - let thread = thread::spawn(move ||{ - loop { - let message = receiver.lock().unwrap().recv().unwrap(); - - match message { - Message::NewJob(job) => { - println!("Worker {} got a job; executing.", id); - - job(); - }, - Message::Terminate => { - println!("Worker {} was told to terminate.", id); - - break; - }, - } - } - }); - - Worker { - id, - thread: Some(thread), - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-23/src/lib.rs:here}} ``` Listing 20-23: Sending and receiving `Message` values and @@ -255,25 +148,7 @@ changing our `Drop` implementation to look like Listing 20-24. Filename: src/lib.rs ```rust,ignore -impl Drop for ThreadPool { - fn drop(&mut self) { - println!("Sending terminate message to all workers."); - - for _ in &mut self.workers { - self.sender.send(Message::Terminate).unwrap(); - } - - println!("Shutting down all workers."); - - for worker in &mut self.workers { - println!("Shutting down worker {}", worker.id); - - if let Some(thread) = worker.thread.take() { - thread.join().unwrap(); - } - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-24/src/lib.rs:here}} ``` Listing 20-24: Sending `Message::Terminate` to the @@ -307,20 +182,7 @@ before gracefully shutting down the server, as shown in Listing 20-25. Filename: src/bin/main.rs ```rust,ignore -fn main() { - let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); - let pool = ThreadPool::new(4); - - for stream in listener.incoming().take(2) { - let stream = stream.unwrap(); - - pool.execute(|| { - handle_connection(stream); - }); - } - - println!("Shutting down."); -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-25/src/bin/main.rs:here}} ``` Listing 20-25: Shut down the server after serving two @@ -337,11 +199,22 @@ end of `main`, and the `drop` implementation will run. Start the server with `cargo run`, and make three requests. The third request should error, and in your terminal you should see output similar to this: + + ```text $ cargo run Compiling hello v0.1.0 (file:///projects/hello) - Finished dev [unoptimized + debuginfo] target(s) in 1.0 secs - Running `target/debug/hello` + Finished dev [unoptimized + debuginfo] target(s) in 1.0s + Running `target/debug/main` Worker 0 got a job; executing. Worker 3 got a job; executing. Shutting down. @@ -383,166 +256,13 @@ Here’s the full code for reference: Filename: src/bin/main.rs ```rust,ignore -use hello::ThreadPool; - -use std::io::prelude::*; -use std::net::TcpListener; -use std::net::TcpStream; -use std::fs; -use std::thread; -use std::time::Duration; - -fn main() { - let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); - let pool = ThreadPool::new(4); - - for stream in listener.incoming().take(2) { - let stream = stream.unwrap(); - - pool.execute(|| { - handle_connection(stream); - }); - } - - println!("Shutting down."); -} - -fn handle_connection(mut stream: TcpStream) { - let mut buffer = [0; 512]; - stream.read(&mut buffer).unwrap(); - - let get = b"GET / HTTP/1.1\r\n"; - let sleep = b"GET /sleep HTTP/1.1\r\n"; - - let (status_line, filename) = if buffer.starts_with(get) { - ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") - } else if buffer.starts_with(sleep) { - thread::sleep(Duration::from_secs(5)); - ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") - } else { - ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") - }; - - let contents = fs::read_to_string(filename).unwrap(); - - let response = format!("{}{}", status_line, contents); - - stream.write(response.as_bytes()).unwrap(); - stream.flush().unwrap(); -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-25/src/bin/main.rs:all}} ``` Filename: src/lib.rs ```rust -use std::thread; -use std::sync::mpsc; -use std::sync::Arc; -use std::sync::Mutex; - -enum Message { - NewJob(Job), - Terminate, -} - -pub struct ThreadPool { - workers: Vec, - sender: mpsc::Sender, -} - -type Job = Box; - -impl ThreadPool { - /// Create a new ThreadPool. - /// - /// The size is the number of threads in the pool. - /// - /// # Panics - /// - /// The `new` function will panic if the size is zero. - pub fn new(size: usize) -> ThreadPool { - assert!(size > 0); - - let (sender, receiver) = mpsc::channel(); - - let receiver = Arc::new(Mutex::new(receiver)); - - let mut workers = Vec::with_capacity(size); - - for id in 0..size { - workers.push(Worker::new(id, Arc::clone(&receiver))); - } - - ThreadPool { - workers, - sender, - } - } - - pub fn execute(&self, f: F) - where - F: FnOnce() + Send + 'static - { - let job = Box::new(f); - - self.sender.send(Message::NewJob(job)).unwrap(); - } -} - -impl Drop for ThreadPool { - fn drop(&mut self) { - println!("Sending terminate message to all workers."); - - for _ in &mut self.workers { - self.sender.send(Message::Terminate).unwrap(); - } - - println!("Shutting down all workers."); - - for worker in &mut self.workers { - println!("Shutting down worker {}", worker.id); - - if let Some(thread) = worker.thread.take() { - thread.join().unwrap(); - } - } - } -} - -struct Worker { - id: usize, - thread: Option>, -} - -impl Worker { - fn new(id: usize, receiver: Arc>>) -> - Worker { - - let thread = thread::spawn(move ||{ - loop { - let message = receiver.lock().unwrap().recv().unwrap(); - - match message { - Message::NewJob(job) => { - println!("Worker {} got a job; executing.", id); - - job(); - }, - Message::Terminate => { - println!("Worker {} was told to terminate.", id); - - break; - }, - } - } - }); - - Worker { - id, - thread: Some(thread), - } - } -} +{{#rustdoc_include ../listings/ch20-web-server/listing-20-25/src/lib.rs:here}} ``` We could do more here! If you want to continue enhancing this project, here are diff --git a/src/doc/book/src/title-page.md b/src/doc/book/src/title-page.md index 5e375d31b4..c1cb567109 100644 --- a/src/doc/book/src/title-page.md +++ b/src/doc/book/src/title-page.md @@ -2,7 +2,7 @@ *by Steve Klabnik and Carol Nichols, with contributions from the Rust Community* -This version of the text assumes you’re using Rust 1.37.0 or later with +This version of the text assumes you’re using Rust 1.41.0 or later with `edition="2018"` in *Cargo.toml* of all projects to use Rust 2018 Edition idioms. See the [“Installation” section of Chapter 1][install] to install or update Rust, and see the new [Appendix E][editions]``, then # Change all remaining links from Markdown to italicized inline text. while IFS= read -r filename; do - < "src/$filename" ./target/release/remove_links \ + < "tmp/markdown/$filename" ./target/release/remove_links \ | ./target/release/link2print \ - | ./target/release/remove_markup > "tmp/$filename" + | ./target/release/remove_markup \ + | ./target/release/remove_hidden_lines > "tmp/$filename" done # Concatenate the files into the `nostarch` dir. ./target/release/concat_chapters tmp nostarch diff --git a/src/doc/book/tools/src/bin/concat_chapters.rs b/src/doc/book/tools/src/bin/concat_chapters.rs index ed992ec906..71fd86f054 100644 --- a/src/doc/book/tools/src/bin/concat_chapters.rs +++ b/src/doc/book/tools/src/bin/concat_chapters.rs @@ -1,13 +1,13 @@ -#[macro_use] extern crate lazy_static; - +#[macro_use] +extern crate lazy_static; +use std::collections::BTreeMap; use std::env; +use std::fs::{create_dir, read_dir, File}; use std::io; use std::io::{Read, Write}; -use std::process::exit; -use std::fs::{create_dir, read_dir, File}; use std::path::{Path, PathBuf}; -use std::collections::BTreeMap; +use std::process::exit; use regex::Regex; @@ -18,7 +18,8 @@ static PATTERNS: &'static [(&'static str, &'static str)] = &[ lazy_static! { static ref MATCHERS: Vec<(Regex, &'static str)> = { - PATTERNS.iter() + PATTERNS + .iter() .map(|&(expr, repl)| (Regex::new(expr).unwrap(), repl)) .collect() }; @@ -43,19 +44,24 @@ fn main() { } } -fn match_files(source_dir: &Path, target_dir: &Path) -> Vec<(PathBuf, PathBuf)> { +fn match_files( + source_dir: &Path, + target_dir: &Path, +) -> Vec<(PathBuf, PathBuf)> { read_dir(source_dir) .expect("Unable to read source directory") .filter_map(|maybe_entry| maybe_entry.ok()) .filter_map(|entry| { let source_filename = entry.file_name(); - let source_filename = &source_filename.to_string_lossy().into_owned(); + let source_filename = + &source_filename.to_string_lossy().into_owned(); for &(ref regex, replacement) in MATCHERS.iter() { if regex.is_match(source_filename) { - let target_filename = regex.replace_all(source_filename, replacement); + let target_filename = + regex.replace_all(source_filename, replacement); let source_path = entry.path(); let mut target_path = PathBuf::from(&target_dir); - target_path.push(target_filename); + target_path.push(target_filename.to_string()); return Some((source_path, target_path)); } } @@ -64,7 +70,9 @@ fn match_files(source_dir: &Path, target_dir: &Path) -> Vec<(PathBuf, PathBuf)> .collect() } -fn group_by_target(matched_files: Vec<(PathBuf, PathBuf)>) -> BTreeMap> { +fn group_by_target( + matched_files: Vec<(PathBuf, PathBuf)>, +) -> BTreeMap> { let mut grouped: BTreeMap> = BTreeMap::new(); for (source, target) in matched_files { if let Some(source_paths) = grouped.get_mut(&target) { @@ -77,7 +85,10 @@ fn group_by_target(matched_files: Vec<(PathBuf, PathBuf)>) -> BTreeMap, target_path: PathBuf) -> io::Result<()> { +fn concat_files( + source_paths: Vec, + target_path: PathBuf, +) -> io::Result<()> { println!("Concatenating into {}:", target_path.to_string_lossy()); let mut target = File::create(target_path)?; target.write_all(b"\n[TOC]\n")?; diff --git a/src/doc/book/tools/src/bin/convert_quotes.rs b/src/doc/book/tools/src/bin/convert_quotes.rs index 027d458d9b..e548c5e075 100644 --- a/src/doc/book/tools/src/bin/convert_quotes.rs +++ b/src/doc/book/tools/src/bin/convert_quotes.rs @@ -12,7 +12,6 @@ fn main() { } for line in buffer.lines() { - if line.is_empty() { is_in_inline_code = false; } @@ -42,29 +41,34 @@ fn main() { } // Replace with right/left apostrophe/quote. - let char_to_push = - if possible_match == '\'' && !is_in_inline_code && !is_in_html_tag { - if (previous_char != std::char::REPLACEMENT_CHARACTER && - !previous_char.is_whitespace()) || - previous_char == '‘' - { - '’' - } else { - '‘' - } - } else if possible_match == '"' && !is_in_inline_code && !is_in_html_tag { - if (previous_char != std::char::REPLACEMENT_CHARACTER && - !previous_char.is_whitespace()) || - previous_char == '“' - { - '”' - } else { - '“' - } + let char_to_push = if possible_match == '\'' + && !is_in_inline_code + && !is_in_html_tag + { + if (previous_char != std::char::REPLACEMENT_CHARACTER + && !previous_char.is_whitespace()) + || previous_char == '‘' + { + '’' + } else { + '‘' + } + } else if possible_match == '"' + && !is_in_inline_code + && !is_in_html_tag + { + if (previous_char != std::char::REPLACEMENT_CHARACTER + && !previous_char.is_whitespace()) + || previous_char == '“' + { + '”' } else { - // Leave untouched. - possible_match - }; + '“' + } + } else { + // Leave untouched. + possible_match + }; modified_line.push(char_to_push); previous_char = char_to_push; } diff --git a/src/doc/book/tools/src/bin/lfp.rs b/src/doc/book/tools/src/bin/lfp.rs index 32b2ab2975..caab7b26e5 100644 --- a/src/doc/book/tools/src/bin/lfp.rs +++ b/src/doc/book/tools/src/bin/lfp.rs @@ -1,30 +1,25 @@ // We have some long regex literals, so: // ignore-tidy-linelength -extern crate docopt; -extern crate rustc_serialize; -extern crate walkdir; - use docopt::Docopt; -use std::{path, fs, io}; +use serde::Deserialize; use std::io::BufRead; +use std::{fs, io, path}; -fn main () { +fn main() { let args: Args = Docopt::new(USAGE) - .and_then(|d| d.decode()) - .unwrap_or_else(|e| e.exit()); + .and_then(|d| d.deserialize()) + .unwrap_or_else(|e| e.exit()); let src_dir = &path::Path::new(&args.arg_src_dir); let found_errs = walkdir::WalkDir::new(src_dir) .min_depth(1) .into_iter() - .map(|entry| { - match entry { - Ok(entry) => entry, - Err(err) => { - eprintln!("{:?}", err); - std::process::exit(911) - }, + .map(|entry| match entry { + Ok(entry) => entry, + Err(err) => { + eprintln!("{:?}", err); + std::process::exit(911) } }) .map(|entry| { @@ -33,10 +28,17 @@ fn main () { let err_vec = lint_file(path); for err in &err_vec { match *err { - LintingError::LineOfInterest(line_num, ref line) => - eprintln!("{}:{}\t{}", path.display(), line_num, line), - LintingError::UnableToOpenFile => - eprintln!("Unable to open {}.", path.display()), + LintingError::LineOfInterest(line_num, ref line) => { + eprintln!( + "{}:{}\t{}", + path.display(), + line_num, + line + ) + } + LintingError::UnableToOpenFile => { + eprintln!("Unable to open {}.", path.display()) + } } } !err_vec.is_empty() @@ -64,7 +66,7 @@ Options: -h --help Show this screen. "; -#[derive(Debug, RustcDecodable)] +#[derive(Debug, Deserialize)] struct Args { arg_src_dir: String, } @@ -77,7 +79,9 @@ fn lint_file(path: &path::Path) -> Vec { } fn lint_lines(lines: I) -> Vec - where I: Iterator> { +where + I: Iterator>, +{ lines .enumerate() .map(|(line_num, line)| { @@ -94,16 +98,16 @@ fn lint_lines(lines: I) -> Vec } fn is_file_of_interest(path: &path::Path) -> bool { - path.extension() - .map_or(false, |ext| ext == "md") + path.extension().map_or(false, |ext| ext == "md") } fn is_line_of_interest(line: &str) -> bool { - !line.split_whitespace() - .filter(|sub_string| - sub_string.contains("file://") && - !sub_string.contains("file:///projects/") - ) + !line + .split_whitespace() + .filter(|sub_string| { + sub_string.contains("file://") + && !sub_string.contains("file:///projects/") + }) .collect::>() .is_empty() } @@ -111,7 +115,7 @@ fn is_line_of_interest(line: &str) -> bool { #[derive(Debug)] enum LintingError { UnableToOpenFile, - LineOfInterest(usize, String) + LineOfInterest(usize, String), } #[cfg(test)] @@ -162,9 +166,7 @@ mod tests { "#; let raw_lines = string.to_string(); - let lines = raw_lines.lines().map(|line| { - Ok(line.to_string()) - }); + let lines = raw_lines.lines().map(|line| Ok(line.to_string())); let result_vec = super::lint_lines(lines); @@ -197,9 +199,7 @@ mod tests { "#; let raw_lines = string.to_string(); - let lines = raw_lines.lines().map(|line| { - Ok(line.to_string()) - }); + let lines = raw_lines.lines().map(|line| Ok(line.to_string())); let result_vec = super::lint_lines(lines); @@ -210,32 +210,41 @@ mod tests { fn is_file_of_interest_returns_false_when_the_path_is_a_directory() { let uninteresting_fn = "src/img"; - assert!(!super::is_file_of_interest(path::Path::new(uninteresting_fn))); + assert!(!super::is_file_of_interest(path::Path::new( + uninteresting_fn + ))); } #[test] - fn is_file_of_interest_returns_false_when_the_filename_does_not_have_the_md_extension() { + fn is_file_of_interest_returns_false_when_the_filename_does_not_have_the_md_extension( + ) { let uninteresting_fn = "src/img/foo1.png"; - assert!(!super::is_file_of_interest(path::Path::new(uninteresting_fn))); + assert!(!super::is_file_of_interest(path::Path::new( + uninteresting_fn + ))); } #[test] - fn is_file_of_interest_returns_true_when_the_filename_has_the_md_extension() { + fn is_file_of_interest_returns_true_when_the_filename_has_the_md_extension() + { let interesting_fn = "src/ch01-00-introduction.md"; assert!(super::is_file_of_interest(path::Path::new(interesting_fn))); } #[test] - fn is_line_of_interest_does_not_report_a_line_if_the_line_contains_a_file_url_which_is_directly_followed_by_the_project_path() { - let sample_line = "Compiling guessing_game v0.1.0 (file:///projects/guessing_game)"; + fn is_line_of_interest_does_not_report_a_line_if_the_line_contains_a_file_url_which_is_directly_followed_by_the_project_path( + ) { + let sample_line = + "Compiling guessing_game v0.1.0 (file:///projects/guessing_game)"; assert!(!super::is_line_of_interest(sample_line)); } #[test] - fn is_line_of_interest_reports_a_line_if_the_line_contains_a_file_url_which_is_not_directly_followed_by_the_project_path() { + fn is_line_of_interest_reports_a_line_if_the_line_contains_a_file_url_which_is_not_directly_followed_by_the_project_path( + ) { let sample_line = "Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game)"; assert!(super::is_line_of_interest(sample_line)); diff --git a/src/doc/book/tools/src/bin/link2print.rs b/src/doc/book/tools/src/bin/link2print.rs index 0d6d2f654a..33d90ec240 100644 --- a/src/doc/book/tools/src/bin/link2print.rs +++ b/src/doc/book/tools/src/bin/link2print.rs @@ -1,12 +1,10 @@ // FIXME: we have some long lines that could be refactored, but it's not a big deal. // ignore-tidy-linelength - - +use regex::{Captures, Regex}; use std::collections::HashMap; use std::io; use std::io::{Read, Write}; -use regex::{Regex, Captures}; fn main() { write_md(parse_links(parse_references(read_md()))); @@ -27,27 +25,29 @@ fn write_md(output: String) { fn parse_references(buffer: String) -> (String, HashMap) { let mut ref_map = HashMap::new(); // FIXME: currently doesn't handle "title" in following line. - let re = Regex::new(r###"(?m)\n?^ {0,3}\[([^]]+)\]:[[:blank:]]*(.*)$"###).unwrap(); + let re = Regex::new(r###"(?m)\n?^ {0,3}\[([^]]+)\]:[[:blank:]]*(.*)$"###) + .unwrap(); let output = re.replace_all(&buffer, |caps: &Captures<'_>| { - let key = caps.at(1).unwrap().to_owned().to_uppercase(); - let val = caps.at(2).unwrap().to_owned(); + let key = caps.get(1).unwrap().as_str().to_uppercase(); + let val = caps.get(2).unwrap().as_str().to_string(); if ref_map.insert(key, val).is_some() { panic!("Did not expect markdown page to have duplicate reference"); } "".to_string() - }); + }).to_string(); (output, ref_map) } fn parse_links((buffer, ref_map): (String, HashMap)) -> String { // FIXME: check which punctuation is allowed by spec. - let re = Regex::new(r###"(?:(?P
(?:```(?:[^`]|`[^`])*`?\n```\n)|(?:[^[]`[^`\n]+[\n]?[^`\n]*`))|(?:\[(?P[^]]+)\](?:(?:\([[:blank:]]*(?P[^")]*[^ ])(?:[[:blank:]]*"[^"]*")?\))|(?:\[(?P[^]]*)\]))?))"###).expect("could not create regex");
-    let error_code = Regex::new(r###"^E\d{4}$"###).expect("could not create regex");
+    let re = Regex::new(r###"(?:(?P
(?:```(?:[^`]|`[^`])*`?\n```\n)|(?:[^\[]`[^`\n]+[\n]?[^`\n]*`))|(?:\[(?P[^]]+)\](?:(?:\([[:blank:]]*(?P[^")]*[^ ])(?:[[:blank:]]*"[^"]*")?\))|(?:\[(?P[^]]*)\]))?))"###).expect("could not create regex");
+    let error_code =
+        Regex::new(r###"^E\d{4}$"###).expect("could not create regex");
     let output = re.replace_all(&buffer, |caps: &Captures<'_>| {
         match caps.name("pre") {
-            Some(pre_section) => format!("{}", pre_section.to_owned()),
+            Some(pre_section) => format!("{}", pre_section.as_str()),
             None => {
-                let name = caps.name("name").expect("could not get name").to_owned();
+                let name = caps.name("name").expect("could not get name").as_str();
                 // Really we should ignore text inside code blocks,
                 // this is a hack to not try to treat `#[derive()]`,
                 // `[profile]`, `[test]`, or `[E\d\d\d\d]` like a link.
@@ -55,21 +55,21 @@ fn parse_links((buffer, ref_map): (String, HashMap)) -> String {
                    name.starts_with("profile") ||
                    name.starts_with("test") ||
                    name.starts_with("no_mangle") ||
-                   error_code.is_match(&name) {
-                    return name
+                   error_code.is_match(name) {
+                    return name.to_string()
                 }
 
                 let val = match caps.name("val") {
                     // `[name](link)`
-                    Some(value) => value.to_owned(),
+                    Some(value) => value.as_str().to_string(),
                     None => {
                         match caps.name("key") {
                             Some(key) => {
-                                match key {
+                                match key.as_str() {
                                     // `[name][]`
                                     "" => format!("{}", ref_map.get(&name.to_uppercase()).expect(&format!("could not find url for the link text `{}`", name))),
                                     // `[name][reference]`
-                                    _ => format!("{}", ref_map.get(&key.to_uppercase()).expect(&format!("could not find url for the link text `{}`", key))),
+                                    _ => format!("{}", ref_map.get(&key.as_str().to_uppercase()).expect(&format!("could not find url for the link text `{}`", key.as_str()))),
                                 }
                             }
                             // `[name]` as reference
@@ -81,7 +81,7 @@ fn parse_links((buffer, ref_map): (String, HashMap)) -> String {
             }
         }
     });
-    output
+    output.to_string()
 }
 
 #[cfg(test)]
@@ -92,8 +92,12 @@ mod tests {
 
     #[test]
     fn parses_inline_link() {
-        let source = r"This is a [link](http://google.com) that should be expanded".to_string();
-        let target = r"This is a link at *http://google.com* that should be expanded".to_string();
+        let source =
+            r"This is a [link](http://google.com) that should be expanded"
+                .to_string();
+        let target =
+            r"This is a link at *http://google.com* that should be expanded"
+                .to_string();
         assert_eq!(parse(source), target);
     }
 
@@ -167,14 +171,18 @@ more text"
 
     #[test]
     fn ignores_optional_inline_title() {
-        let source = r###"This is a titled [link](http://example.com "My title")."###.to_string();
-        let target = r"This is a titled link at *http://example.com*.".to_string();
+        let source =
+            r###"This is a titled [link](http://example.com "My title")."###
+                .to_string();
+        let target =
+            r"This is a titled link at *http://example.com*.".to_string();
         assert_eq!(parse(source), target);
     }
 
     #[test]
     fn parses_title_with_puctuation() {
-        let source = r###"[link](http://example.com "It's Title")"###.to_string();
+        let source =
+            r###"[link](http://example.com "It's Title")"###.to_string();
         let target = r"link at *http://example.com*".to_string();
         assert_eq!(parse(source), target);
     }
@@ -188,11 +196,11 @@ more text"
     #[test]
     fn parses_name_with_utf8() {
         let source = r###"[user’s forum](the user’s forum)"###.to_string();
-        let target = r###"user’s forum at *the user’s forum*"###.to_string();
+        let target =
+            r###"user’s forum at *the user’s forum*"###.to_string();
         assert_eq!(parse(source), target);
     }
 
-
     #[test]
     fn parses_reference_with_punctuation() {
         let source = r###"[link][the ref-ref]
@@ -248,7 +256,7 @@ authors = ["Your Name "]
 [dependencies]
 ```
 "###
-            .to_string();
+        .to_string();
         let target = source.clone();
         assert_eq!(parse(source), target);
     }
@@ -284,7 +292,7 @@ Another [link]
 more text
 [link]: http://gohere
 "###
-            .to_string();
+        .to_string();
         let target = r###"```toml
 [package]
 name = "hello_cargo"
@@ -296,7 +304,7 @@ authors = ["Your Name "]
 Another link at *http://gohere*
 more text
 "###
-            .to_string();
+        .to_string();
         assert_eq!(parse(source), target);
     }
     #[test]
diff --git a/src/doc/book/tools/src/bin/release_listings.rs b/src/doc/book/tools/src/bin/release_listings.rs
new file mode 100644
index 0000000000..56a38e020c
--- /dev/null
+++ b/src/doc/book/tools/src/bin/release_listings.rs
@@ -0,0 +1,159 @@
+#[macro_use]
+extern crate lazy_static;
+
+use regex::Regex;
+use std::error::Error;
+use std::fs;
+use std::fs::File;
+use std::io::prelude::*;
+use std::io::{BufReader, BufWriter};
+use std::path::{Path, PathBuf};
+
+fn main() -> Result<(), Box> {
+    // Get all listings from the `listings` directory
+    let listings_dir = Path::new("listings");
+
+    // Put the results in the `tmp/listings` directory
+    let out_dir = Path::new("tmp/listings");
+
+    // Clear out any existing content in `tmp/listings`
+    if out_dir.is_dir() {
+        fs::remove_dir_all(out_dir)?;
+    }
+
+    // Create a new, empty `tmp/listings` directory
+    fs::create_dir(out_dir)?;
+
+    // For each chapter in the `listings` directory,
+    for chapter in fs::read_dir(listings_dir)? {
+        let chapter = chapter?;
+        let chapter_path = chapter.path();
+
+        let chapter_name = chapter_path
+            .file_name()
+            .expect("Chapter should've had a name");
+
+        // Create a corresponding chapter dir in `tmp/listings`
+        let output_chapter_path = out_dir.join(chapter_name);
+        fs::create_dir(&output_chapter_path)?;
+
+        // For each listing in the chapter directory,
+        for listing in fs::read_dir(chapter_path)? {
+            let listing = listing?;
+            let listing_path = listing.path();
+
+            let listing_name = listing_path
+                .file_name()
+                .expect("Listing should've had a name");
+
+            // Create a corresponding listing dir in the tmp chapter dir
+            let output_listing_dir = output_chapter_path.join(listing_name);
+            fs::create_dir(&output_listing_dir)?;
+
+            // Copy all the cleaned files in the listing to the tmp directory
+            copy_cleaned_listing_files(listing_path, output_listing_dir)?;
+        }
+    }
+
+    // Create a compressed archive of all the listings
+    let tarfile = File::create("tmp/listings.tar.gz")?;
+    let encoder =
+        flate2::write::GzEncoder::new(tarfile, flate2::Compression::default());
+    let mut archive = tar::Builder::new(encoder);
+    archive.append_dir_all("listings", "tmp/listings")?;
+
+    // Assure whoever is running this that the script exiting successfully, and remind them
+    // where the generated file ends up
+    println!("Release tarball of listings in tmp/listings.tar.gz");
+
+    Ok(())
+}
+
+// Cleaned listings will not contain:
+//
+// - `target` directories
+// - `output.txt` files used to display output in the book
+// - `rustfmt-ignore` files used to signal to update-rustc.sh the listing shouldn't be formatted
+// - anchor comments or snip comments
+// - empty `main` functions in `lib.rs` files used to trick rustdoc
+fn copy_cleaned_listing_files(
+    from: PathBuf,
+    to: PathBuf,
+) -> Result<(), Box> {
+    for item in fs::read_dir(from)? {
+        let item = item?;
+        let item_path = item.path();
+
+        let item_name =
+            item_path.file_name().expect("Item should've had a name");
+        let output_item = to.join(item_name);
+
+        if item_path.is_dir() {
+            // Don't copy `target` directories
+            if item_name != "target" {
+                fs::create_dir(&output_item)?;
+                copy_cleaned_listing_files(item_path, output_item)?;
+            }
+        } else {
+            // Don't copy output files or files that tell update-rustc.sh not to format
+            if item_name != "output.txt" && item_name != "rustfmt-ignore" {
+                let item_extension = item_path.extension();
+                if item_extension.is_some() && item_extension.unwrap() == "rs" {
+                    copy_cleaned_rust_file(
+                        item_name,
+                        &item_path,
+                        &output_item,
+                    )?;
+                } else {
+                    // Copy any non-Rust files without modification
+                    fs::copy(item_path, output_item)?;
+                }
+            }
+        }
+    }
+
+    Ok(())
+}
+
+lazy_static! {
+    static ref ANCHOR_OR_SNIP_COMMENTS: Regex = Regex::new(
+        r"(?x)
+    //\s*ANCHOR:\s*[\w_-]+      # Remove all anchor comments
+    |
+    //\s*ANCHOR_END:\s*[\w_-]+  # Remove all anchor ending comments
+    |
+    //\s*--snip--               # Remove all snip comments
+    "
+    )
+    .unwrap();
+}
+
+lazy_static! {
+    static ref EMPTY_MAIN: Regex = Regex::new(r"fn main\(\) \{}").unwrap();
+}
+
+// Cleaned Rust files will not contain:
+//
+// - anchor comments or snip comments
+// - empty `main` functions in `lib.rs` files used to trick rustdoc
+fn copy_cleaned_rust_file(
+    item_name: &std::ffi::OsStr,
+    from: &PathBuf,
+    to: &PathBuf,
+) -> Result<(), Box> {
+    let from_buf = BufReader::new(File::open(from)?);
+    let mut to_buf = BufWriter::new(File::create(to)?);
+
+    for line in from_buf.lines() {
+        let line = line?;
+        if !ANCHOR_OR_SNIP_COMMENTS.is_match(&line) {
+            if item_name != "lib.rs" || !EMPTY_MAIN.is_match(&line) {
+                writeln!(&mut to_buf, "{}", line)?;
+            }
+        }
+    }
+
+    to_buf.flush()?;
+
+    Ok(())
+}
diff --git a/src/doc/book/tools/src/bin/remove_hidden_lines.rs b/src/doc/book/tools/src/bin/remove_hidden_lines.rs
new file mode 100644
index 0000000000..fa3b705210
--- /dev/null
+++ b/src/doc/book/tools/src/bin/remove_hidden_lines.rs
@@ -0,0 +1,83 @@
+use std::io;
+use std::io::prelude::*;
+
+fn main() {
+    write_md(remove_hidden_lines(&read_md()));
+}
+
+fn read_md() -> String {
+    let mut buffer = String::new();
+    match io::stdin().read_to_string(&mut buffer) {
+        Ok(_) => buffer,
+        Err(error) => panic!(error),
+    }
+}
+
+fn write_md(output: String) {
+    write!(io::stdout(), "{}", output).unwrap();
+}
+
+fn remove_hidden_lines(input: &str) -> String {
+    let mut resulting_lines = vec![];
+    let mut within_codeblock = false;
+
+    for line in input.lines() {
+        if line.starts_with("```") {
+            within_codeblock = !within_codeblock;
+        }
+
+        if !within_codeblock || (!line.starts_with("# ") && line != "#") {
+            resulting_lines.push(line)
+        }
+    }
+
+    resulting_lines.join("\n")
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::remove_hidden_lines;
+
+    #[test]
+    fn hidden_line_in_code_block_is_removed() {
+        let input = r#"
+In this listing:
+
+```
+fn main() {
+# secret
+}
+```
+
+you can see that...
+        "#;
+        let output = remove_hidden_lines(input);
+
+        let desired_output = r#"
+In this listing:
+
+```
+fn main() {
+}
+```
+
+you can see that...
+        "#;
+
+        assert_eq!(output, desired_output);
+    }
+
+    #[test]
+    fn headings_arent_removed() {
+        let input = r#"
+# Heading 1
+        "#;
+        let output = remove_hidden_lines(input);
+
+        let desired_output = r#"
+# Heading 1
+        "#;
+
+        assert_eq!(output, desired_output);
+    }
+}
diff --git a/src/doc/book/tools/src/bin/remove_links.rs b/src/doc/book/tools/src/bin/remove_links.rs
index b31d7dc615..a096389b83 100644
--- a/src/doc/book/tools/src/bin/remove_links.rs
+++ b/src/doc/book/tools/src/bin/remove_links.rs
@@ -1,11 +1,11 @@
 extern crate regex;
 
+use regex::{Captures, Regex};
 use std::collections::HashSet;
 use std::io;
 use std::io::{Read, Write};
-use regex::{Regex, Captures};
 
-fn main () {
+fn main() {
     let mut buffer = String::new();
     if let Err(e) = io::stdin().read_to_string(&mut buffer) {
         panic!(e);
@@ -14,23 +14,23 @@ fn main () {
     let mut refs = HashSet::new();
 
     // Capture all links and link references.
-    let regex = r"\[([^\]]+)\](?:(?:\[([^\]]+)\])|(?:\([^\)]+\)))(?i)";
+    let regex =
+        r"\[([^\]]+)\](?:(?:\[([^\]]+)\])|(?:\([^\)]+\)))(?i)";
     let link_regex = Regex::new(regex).unwrap();
     let first_pass = link_regex.replace_all(&buffer, |caps: &Captures<'_>| {
-
         // Save the link reference we want to delete.
-        if let Some(reference) = caps.at(2) {
-            refs.insert(reference.to_owned());
+        if let Some(reference) = caps.get(2) {
+            refs.insert(reference.as_str().to_string());
         }
 
         // Put the link title back.
-        caps.at(1).unwrap().to_owned()
+        caps.get(1).unwrap().as_str().to_string()
     });
 
     // Search for the references we need to delete.
     let ref_regex = Regex::new(r"(?m)^\[([^\]]+)\]:\s.*\n").unwrap();
     let out = ref_regex.replace_all(&first_pass, |caps: &Captures<'_>| {
-        let capture = caps.at(1).unwrap().to_owned();
+        let capture = caps.get(1).unwrap().to_owned();
 
         // Check if we've marked this reference for deletion ...
         if refs.contains(capture.as_str()) {
@@ -38,7 +38,7 @@ fn main () {
         }
 
         // ... else we put back everything we captured.
-        caps.at(0).unwrap().to_owned()
+        caps.get(0).unwrap().as_str().to_string()
     });
 
     write!(io::stdout(), "{}", out).unwrap();
diff --git a/src/doc/book/tools/src/bin/remove_markup.rs b/src/doc/book/tools/src/bin/remove_markup.rs
index a4d352d131..8877e038f7 100644
--- a/src/doc/book/tools/src/bin/remove_markup.rs
+++ b/src/doc/book/tools/src/bin/remove_markup.rs
@@ -1,8 +1,8 @@
 extern crate regex;
 
+use regex::{Captures, Regex};
 use std::io;
 use std::io::{Read, Write};
-use regex::{Regex, Captures};
 
 fn main() {
     write_md(remove_markup(read_md()));
@@ -21,25 +21,31 @@ fn write_md(output: String) {
 }
 
 fn remove_markup(input: String) -> String {
-    let filename_regex = Regex::new(r#"\A(.*)\z"#).unwrap();
+    let filename_regex =
+        Regex::new(r#"\A(.*)\z"#).unwrap();
     // Captions sometimes take up multiple lines.
-    let caption_start_regex = Regex::new(r#"\A(.*)\z"#).unwrap();
+    let caption_start_regex =
+        Regex::new(r#"\A(.*)\z"#).unwrap();
     let caption_end_regex = Regex::new(r#"(.*)\z"#).unwrap();
     let regexen = vec![filename_regex, caption_start_regex, caption_end_regex];
 
-    let lines: Vec<_> = input.lines().flat_map(|line| {
-        // Remove our syntax highlighting and rustdoc markers.
-        if line.starts_with("```") {
-            Some(String::from("```"))
-        // Remove the span around filenames and captions.
-        } else {
-            let result = regexen.iter().fold(line.to_string(), |result, regex| {
-                regex.replace_all(&result, |caps: &Captures<'_>| {
-                    caps.at(1).unwrap().to_owned()
-                })
-            });
-            Some(result)
-        }
-    }).collect();
+    let lines: Vec<_> = input
+        .lines()
+        .flat_map(|line| {
+            // Remove our syntax highlighting and rustdoc markers.
+            if line.starts_with("```") {
+                Some(String::from("```"))
+            // Remove the span around filenames and captions.
+            } else {
+                let result =
+                    regexen.iter().fold(line.to_string(), |result, regex| {
+                        regex.replace_all(&result, |caps: &Captures<'_>| {
+                            caps.get(1).unwrap().as_str().to_string()
+                        }).to_string()
+                    });
+                Some(result)
+            }
+        })
+        .collect();
     lines.join("\n")
 }
diff --git a/src/doc/book/tools/update-rustc.sh b/src/doc/book/tools/update-rustc.sh
new file mode 100755
index 0000000000..201f076ffa
--- /dev/null
+++ b/src/doc/book/tools/update-rustc.sh
@@ -0,0 +1,76 @@
+#!/bin/bash
+
+set -eu
+
+# Build the book before making any changes for comparison of the output.
+echo 'Building book into `tmp/book-before` before updating...'
+mdbook build -d tmp/book-before
+
+# Rustfmt all listings
+echo 'Formatting all listings...'
+find -s listings -name Cargo.toml -print0 | while IFS= read -r -d '' f; do
+    dir_to_fmt=$(dirname $f)
+
+    # There are a handful of listings we don't want to rustfmt and skipping doesn't work;
+    # those will have a file in their directory that explains why.
+    if [ ! -f "${dir_to_fmt}/rustfmt-ignore" ]; then
+        cd $dir_to_fmt
+        cargo fmt --all && true
+        cd - > /dev/null
+    fi
+done
+
+# Get listings without anchor comments in tmp by compiling a release listings artifact
+echo 'Generate listings without anchor comments...'
+cargo run --bin release_listings
+
+root_dir=$(pwd)
+
+echo 'Regenerating output...'
+# For any listings where we show the output,
+find -s listings -name output.txt -print0 | while IFS= read -r -d '' f; do
+    build_directory=$(dirname $f)
+    full_build_directory="${root_dir}/${build_directory}"
+    full_output_path="${full_build_directory}/output.txt"
+    tmp_build_directory="tmp/${build_directory}"
+
+    cd $tmp_build_directory
+
+    # Save the previous compile time; we're going to keep it to minimize diff churn
+    compile_time=$(sed -E -ne "s/.*Finished (dev|test) \[unoptimized \+ debuginfo] target\(s\) in ([0-9.]*).*/\2/p" ${full_output_path})
+
+    # Act like this is the first time this listing has been built
+    cargo clean
+
+    # Run the command in the existing output file
+    cargo_command=$(sed -ne "s/$ \(.*\)/\1/p" ${full_output_path})
+
+    # Clear the output file of everything except the command
+    echo "$ ${cargo_command}" > ${full_output_path}
+
+    # Regenerate the output and append to the output file. Turn some warnings
+    # off to reduce output noise, and use one test thread to get consistent
+    # ordering of tests in the output when the command is `cargo test`.
+    RUSTFLAGS="-A unused_variables -A dead_code" RUST_TEST_THREADS=1 $cargo_command >> ${full_output_path} 2>&1 || true
+
+    # Set the project file path to the projects directory plus the crate name instead of a path
+    # to the computer of whoever is running this
+    sed -i '' -E -e "s/(Compiling|Checking) ([^\)]*) v0.1.0 (.*)/\1 \2 v0.1.0 (file:\/\/\/projects\/\2)/" ${full_output_path}
+
+    # Restore the previous compile time, if there is one
+    if [ -n  "${compile_time}" ]; then
+        sed -i '' -E -e "s/Finished (dev|test) \[unoptimized \+ debuginfo] target\(s\) in [0-9.]*/Finished \1 [unoptimized + debuginfo] target(s) in ${compile_time}/" ${full_output_path}
+    fi
+
+    cd - > /dev/null
+done
+
+# Build the book after making all the changes
+echo 'Building book into `tmp/book-after` after updating...'
+mdbook build -d tmp/book-after
+
+# Run the megadiff script that removes all files that are the same, leaving only files to audit
+echo 'Removing tmp files that had no changes from the update...'
+./tools/megadiff.sh
+
+echo 'Done.'
diff --git a/src/doc/edition-guide/src/rust-2018/cargo-and-crates-io/cargo-check-for-faster-checking.md b/src/doc/edition-guide/src/rust-2018/cargo-and-crates-io/cargo-check-for-faster-checking.md
index 39812f703c..e3883f3b71 100644
--- a/src/doc/edition-guide/src/rust-2018/cargo-and-crates-io/cargo-check-for-faster-checking.md
+++ b/src/doc/edition-guide/src/rust-2018/cargo-and-crates-io/cargo-check-for-faster-checking.md
@@ -14,7 +14,7 @@ correct, all that stuff. Second, once it's satisfied that everything is in
 order, it produces the actual binary code that you end up executing.
 
 It turns out that that second step takes a lot of time. And most of the time,
-it's not neccesary. That is, when you're working on some Rust code, many
+it's not necessary. That is, when you're working on some Rust code, many
 developers will get into a workflow like this:
 
 1. Write some code.
diff --git a/src/doc/embedded-book/ci/install.sh b/src/doc/embedded-book/ci/install.sh
index dd5b2a8df0..08e3d24e51 100644
--- a/src/doc/embedded-book/ci/install.sh
+++ b/src/doc/embedded-book/ci/install.sh
@@ -2,14 +2,14 @@ set -euxo pipefail
 
 main() {
     local tag=$(git ls-remote --tags --refs --exit-code \
-                    https://github.com/rust-lang-nursery/mdbook \
+                    https://github.com/rust-lang/mdbook \
                         | cut -d/ -f3 \
                         | grep -E '^v[0-9\.]+$' \
                         | sort --version-sort \
                         | tail -n1)
 
     curl -LSfs https://japaric.github.io/trust/install.sh | \
-        sh -s -- --git rust-lang-nursery/mdbook --tag $tag
+        sh -s -- --git rust-lang/mdbook --tag $tag
 
     pip install linkchecker --user
 }
diff --git a/src/doc/embedded-book/ci/script.sh b/src/doc/embedded-book/ci/script.sh
index afb41fa550..6d9cad348d 100644
--- a/src/doc/embedded-book/ci/script.sh
+++ b/src/doc/embedded-book/ci/script.sh
@@ -4,15 +4,13 @@ main() {
     mdbook build
     mdbook test
 
-    # FIXME(rust-lang-nursery/mdbook#789) remove `--ignore-url` when that bug is fixed
-    linkchecker --ignore-url "print.html" book
+    linkchecker book
 
     # now check this as a directory of the bookshelf
     rm -rf shelf
     mkdir shelf
     mv book shelf
-    # FIXME(rust-lang-nursery/mdbook#789) remove `--ignore-url` when that bug is fixed
-    linkchecker --ignore-url "print.html" shelf
+    linkchecker shelf
 
     mv shelf/book .
     rmdir shelf
diff --git a/src/doc/embedded-book/src/SUMMARY.md b/src/doc/embedded-book/src/SUMMARY.md
index 8614cee72b..f0f29a0270 100644
--- a/src/doc/embedded-book/src/SUMMARY.md
+++ b/src/doc/embedded-book/src/SUMMARY.md
@@ -46,3 +46,7 @@ more information and coordination
     - [A little Rust with your C](./interoperability/rust-with-c.md)
 - [Unsorted topics](./unsorted/index.md)
   - [Optimizations: The speed size tradeoff](./unsorted/speed-vs-size.md)
+
+---
+
+[Appendix A: Glossary](./appendix/glossary.md)
diff --git a/src/doc/embedded-book/src/appendix/glossary.md b/src/doc/embedded-book/src/appendix/glossary.md
new file mode 100644
index 0000000000..e0e7d4a10a
--- /dev/null
+++ b/src/doc/embedded-book/src/appendix/glossary.md
@@ -0,0 +1,16 @@
+# Appendix A: Glossary
+
+The embedded ecosystem is full of different protocols, hardware components and
+vendor-specific things that use their own terms and abbreviations. This Glossary
+attempts to list them with pointers for understanding them better.
+
+Term         | Meaning
+-------------|--------
+I2C          | Sometimes referred to as `I² C` or Inter-IC. It is a protocol meant for hardware communication within a single integrated circuit. See [i2c.info] for more details
+SPI          | Serial Peripheral Interface
+USART        | Universal synchronous and asynchronous receiver-transmitter
+UART         | Universal asynchronous receiver-transmitter
+FPU          | Floating-point Unit. A 'math processor' running only operations on floating-point numbers
+PAC          | Peripheral Access Crate
+
+[i2c.info]: https://i2c.info/
diff --git a/src/doc/embedded-book/src/interoperability/c-with-rust.md b/src/doc/embedded-book/src/interoperability/c-with-rust.md
index bf88fd03ab..ab06519020 100644
--- a/src/doc/embedded-book/src/interoperability/c-with-rust.md
+++ b/src/doc/embedded-book/src/interoperability/c-with-rust.md
@@ -87,7 +87,7 @@ Rather than manually generating these interfaces, which may be tedious and error
   `--ctypes-prefix=cty` and `Builder.use_core()` to make the generated code `#![no_std]` compatible.
 4. `bindgen` will produce the generated Rust code to the output of the terminal window. This file may be piped to a file in your project, such as `bindings.rs`. You may use this file in your Rust project to interact with C/C++ code compiled and linked as an external library. Tip: don't forget to use the [`cty`](https://crates.io/crates/cty) crate if your types in the generated bindings are prefixed with `cty`.
 
-[bindgen]: https://github.com/rust-lang-nursery/rust-bindgen
+[bindgen]: https://github.com/rust-lang/rust-bindgen
 [bindgen user's manual]: https://rust-lang.github.io/rust-bindgen/
 
 ## Building your C/C++ code
diff --git a/src/doc/embedded-book/src/intro/index.md b/src/doc/embedded-book/src/intro/index.md
index d4304f0050..5ccc3ff54b 100644
--- a/src/doc/embedded-book/src/intro/index.md
+++ b/src/doc/embedded-book/src/intro/index.md
@@ -56,6 +56,7 @@ If you are unfamiliar with anything mentioned above or if you want more informat
 | Topic        | Resource | Description |
 |--------------|----------|-------------|
 | Rust         | [Rust Book](https://doc.rust-lang.org/book/) | If you are not yet comfortable with Rust, we highly suggest reading this book. |
+| Rust, Embedded | [Discovery Book](https://docs.rust-embedded.org/discovery/) | If you have never done any embedded programming, this book might be a better start |
 | Rust, Embedded | [Embedded Rust Bookshelf](https://docs.rust-embedded.org) | Here you can find several other resources provided by Rust's Embedded Working Group. |
 | Rust, Embedded | [Embedonomicon](https://docs.rust-embedded.org/embedonomicon/) | The nitty gritty details when doing embedded programming in Rust. |
 | Rust, Embedded | [embedded FAQ](https://docs.rust-embedded.org/faq.html) | Frequently asked questions about Rust in an embedded context. |
@@ -97,3 +98,22 @@ it should be reported in [the issue tracker] of this book.
 [the issue tracker]: https://github.com/rust-embedded/book/issues/
 
 Pull requests fixing typos and adding new content are very welcome!
+
+## Re-using this material
+
+This book is distributed under the following licenses:
+
+* The code samples and free-standing Cargo projects contained within this book are licensed under the terms of both the [MIT License] and the [Apache License v2.0].
+* The written prose, pictures and diagrams contained within this book are licensed under the terms of the Creative Commons [CC-BY-SA v4.0] license.
+
+[MIT License]: https://opensource.org/licenses/MIT
+[Apache License v2.0]: http://www.apache.org/licenses/LICENSE-2.0
+[CC-BY-SA v4.0]: https://creativecommons.org/licenses/by-sa/4.0/legalcode
+
+TL;DR: If you want to use our text or images in your work, you need to:
+
+* Give the appropriate credit (i.e. mention this book on your slide, and provide a link to the relevant page)
+* Provide a link to the [CC-BY-SA v4.0] licence
+* Indicate if you have changed the material in any way, and make any changes to our material available under the same licence
+
+Also, please do let us know if you find this book useful!
diff --git a/src/doc/embedded-book/src/static-guarantees/design-contracts.md b/src/doc/embedded-book/src/static-guarantees/design-contracts.md
index 6c3af65db9..56fec45bea 100644
--- a/src/doc/embedded-book/src/static-guarantees/design-contracts.md
+++ b/src/doc/embedded-book/src/static-guarantees/design-contracts.md
@@ -239,7 +239,7 @@ let pin_state = pulled_low.bit_is_set();
  * Example 3: Pulled Low input to Output, set high
  */
 let output_pin = pulled_low.into_enabled_output();
-output_pin.set_bit(false);
+output_pin.set_bit(true);
 
 // Can't do this, output pins don't have this interface!
 // output_pin.into_input_pull_down();
diff --git a/src/doc/embedded-book/src/static-guarantees/typestate-programming.md b/src/doc/embedded-book/src/static-guarantees/typestate-programming.md
index 9f21150315..9bd70f40d7 100644
--- a/src/doc/embedded-book/src/static-guarantees/typestate-programming.md
+++ b/src/doc/embedded-book/src/static-guarantees/typestate-programming.md
@@ -6,40 +6,42 @@ The concept of [typestates] describes the encoding of information about the curr
 [Builder Pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
 
 ```rust
-#[derive(Debug)]
-struct Foo {
-    inner: u32,
-}
+pub mod foo_module {
+    #[derive(Debug)]
+    pub struct Foo {
+        inner: u32,
+    }
 
-struct FooBuilder {
-    a: u32,
-    b: u32,
-}
+    pub struct FooBuilder {
+        a: u32,
+        b: u32,
+    }
 
-impl FooBuilder {
-    pub fn new(starter: u32) -> Self {
-        Self {
-            a: starter,
-            b: starter,
+    impl FooBuilder {
+        pub fn new(starter: u32) -> Self {
+            Self {
+                a: starter,
+                b: starter,
+            }
         }
-    }
 
-    pub fn double_a(self) -> Self {
-        Self {
-            a: self.a * 2,
-            b: self.b,
+        pub fn double_a(self) -> Self {
+            Self {
+                a: self.a * 2,
+                b: self.b,
+            }
         }
-    }
 
-    pub fn into_foo(self) -> Foo {
-        Foo {
-            inner: self.a + self.b,
+        pub fn into_foo(self) -> Foo {
+            Foo {
+                inner: self.a + self.b,
+            }
         }
     }
 }
 
 fn main() {
-    let x = FooBuilder::new(10)
+    let x = foo_module::FooBuilder::new(10)
         .double_a()
         .into_foo();
 
@@ -60,4 +62,4 @@ Because Rust has a [Strong Type System], there is no easy way to magically creat
 
 [Strong Type System]: https://en.wikipedia.org/wiki/Strong_and_weak_typing
 
-This allows us to represent the states of our system as types, and to include the necessary actions for state transitions into the methods that exchange one type for another. By creating a `FooBuilder`, and exchanging it for a `Foo` object, we have walked through the steps of a basic state machine.
\ No newline at end of file
+This allows us to represent the states of our system as types, and to include the necessary actions for state transitions into the methods that exchange one type for another. By creating a `FooBuilder`, and exchanging it for a `Foo` object, we have walked through the steps of a basic state machine.
diff --git a/src/doc/nomicon/book.toml b/src/doc/nomicon/book.toml
new file mode 100644
index 0000000000..37984f1300
--- /dev/null
+++ b/src/doc/nomicon/book.toml
@@ -0,0 +1,7 @@
+[book]
+author = "The Rust Project Developers"
+title = "The Rustonomicon"
+description = "The Dark Arts of Advanced and Unsafe Rust Programming"
+
+[output.html]
+git-repository-url = "https://github.com/rust-lang/nomicon"
diff --git a/src/doc/nomicon/src/destructors.md b/src/doc/nomicon/src/destructors.md
index ae91096a77..6893759776 100644
--- a/src/doc/nomicon/src/destructors.md
+++ b/src/doc/nomicon/src/destructors.md
@@ -28,7 +28,7 @@ For instance, a custom implementation of `Box` might write `Drop` like this:
 ```rust
 #![feature(ptr_internals, allocator_api)]
 
-use std::alloc::{Alloc, Global, GlobalAlloc, Layout};
+use std::alloc::{AllocRef, Global, GlobalAlloc, Layout};
 use std::mem;
 use std::ptr::{drop_in_place, NonNull, Unique};
 
@@ -55,7 +55,7 @@ However this wouldn't work:
 ```rust
 #![feature(allocator_api, ptr_internals)]
 
-use std::alloc::{Alloc, Global, GlobalAlloc, Layout};
+use std::alloc::{AllocRef, Global, GlobalAlloc, Layout};
 use std::ptr::{drop_in_place, Unique, NonNull};
 use std::mem;
 
@@ -128,7 +128,7 @@ of Self during `drop` is to use an Option:
 ```rust
 #![feature(allocator_api, ptr_internals)]
 
-use std::alloc::{Alloc, GlobalAlloc, Global, Layout};
+use std::alloc::{AllocRef, GlobalAlloc, Global, Layout};
 use std::ptr::{drop_in_place, Unique, NonNull};
 use std::mem;
 
diff --git a/src/doc/nomicon/src/ffi.md b/src/doc/nomicon/src/ffi.md
index d766cf26a6..fdb9ff0a8d 100644
--- a/src/doc/nomicon/src/ffi.md
+++ b/src/doc/nomicon/src/ffi.md
@@ -662,13 +662,13 @@ fairly easy, but requires a few things:
 
 ```rust
 #[no_mangle]
-pub extern fn hello_rust() -> *const u8 {
+pub extern "C" fn hello_rust() -> *const u8 {
     "Hello, world!\0".as_ptr()
 }
 # fn main() {}
 ```
 
-The `extern` makes this function adhere to the C calling convention, as
+The `extern "C"` makes this function adhere to the C calling convention, as
 discussed above in "[Foreign Calling
 Conventions](ffi.html#foreign-calling-conventions)". The `no_mangle`
 attribute turns off Rust's name mangling, so that it is easier to link to.
diff --git a/src/doc/nomicon/src/lifetimes.md b/src/doc/nomicon/src/lifetimes.md
index bc917b14dd..649cd770a2 100644
--- a/src/doc/nomicon/src/lifetimes.md
+++ b/src/doc/nomicon/src/lifetimes.md
@@ -261,6 +261,8 @@ data.push(4);
 // Here, the destructor is run and therefore this'll fail to compile.
 ```
 
+One way to convince the compiler that `x` is no longer valid is by using `drop(x)` before `data.push(4)`.
+
 Furthermore, there might be multiple possible last uses of the borrow, for
 example in each branch of a condition.
 
diff --git a/src/doc/nomicon/src/safe-unsafe-meaning.md b/src/doc/nomicon/src/safe-unsafe-meaning.md
index e231384314..0418f6df9c 100644
--- a/src/doc/nomicon/src/safe-unsafe-meaning.md
+++ b/src/doc/nomicon/src/safe-unsafe-meaning.md
@@ -56,7 +56,7 @@ implementations have generally been rigorously manually checked, so the Safe Rus
 interfaces built on top of these implementations can be assumed to be safe.
 
 The need for all of this separation boils down a single fundamental property
-of Safe Rust:
+of Safe Rust, the *soundness property*:
 
 **No matter what, Safe Rust can't cause Undefined Behavior.**
 
diff --git a/src/doc/nomicon/src/subtyping.md b/src/doc/nomicon/src/subtyping.md
index 9c362a2840..79b6408350 100644
--- a/src/doc/nomicon/src/subtyping.md
+++ b/src/doc/nomicon/src/subtyping.md
@@ -183,10 +183,10 @@ to trying to explain:
 The types with \*'s are the ones we will be focusing on, as they are in
 some sense "fundamental". All the others can be understood by analogy to the others:
 
-* Vec and all other owning pointers and collections follow the same logic as Box
-* Cell and all other interior mutability types follow the same logic as UnsafeCell
-* `*const` follows the logic of `&T`
-* `*mut` follows the logic of `&mut T` (or `UnsafeCell`)
+* `Vec` and all other owning pointers and collections follow the same logic as `Box`
+* `Cell` and all other interior mutability types follow the same logic as `UnsafeCell`
+* `*const T` follows the logic of `&T`
+* `*mut T` follows the logic of `&mut T` (or `UnsafeCell`)
 
 > NOTE: the *only* source of contravariance in the language is the arguments to
 > a function, which is why it really doesn't come up much in practice. Invoking
diff --git a/src/doc/nomicon/src/vec-alloc.md b/src/doc/nomicon/src/vec-alloc.md
index 2889a731dd..694059d51c 100644
--- a/src/doc/nomicon/src/vec-alloc.md
+++ b/src/doc/nomicon/src/vec-alloc.md
@@ -37,7 +37,7 @@ that, we'll need to use the rest of the heap APIs. These basically allow us to
 talk directly to Rust's allocator (jemalloc by default).
 
 We'll also need a way to handle out-of-memory (OOM) conditions. The standard
-library calls `std::alloc::oom()`, which in turn calls the the `oom` langitem,
+library calls `std::alloc::oom()`, which in turn calls the `oom` langitem,
 which aborts the program in a platform-specific manner.
 The reason we abort and don't panic is because unwinding can cause allocations
 to happen, and that seems like a bad thing to do when your allocator just came
diff --git a/src/doc/nomicon/src/vec-final.md b/src/doc/nomicon/src/vec-final.md
index 66c8e8bcba..a858547eb1 100644
--- a/src/doc/nomicon/src/vec-final.md
+++ b/src/doc/nomicon/src/vec-final.md
@@ -9,7 +9,7 @@ use std::ptr::{Unique, NonNull, self};
 use std::mem;
 use std::ops::{Deref, DerefMut};
 use std::marker::PhantomData;
-use std::alloc::{Alloc, GlobalAlloc, Layout, Global, handle_alloc_error};
+use std::alloc::{AllocRef, GlobalAlloc, Layout, Global, handle_alloc_error};
 
 struct RawVec {
     ptr: Unique,
@@ -52,7 +52,7 @@ impl RawVec {
                     mem::align_of::(),
                 ))
             }
-            let ptr = ptr.unwrap();
+            let (ptr, _) = ptr.unwrap();
 
             self.ptr = Unique::new_unchecked(ptr.as_ptr() as *mut _);
             self.cap = new_cap;
diff --git a/src/doc/reference/src/attributes.md b/src/doc/reference/src/attributes.md
index dfffe5ca01..da94428ea4 100644
--- a/src/doc/reference/src/attributes.md
+++ b/src/doc/reference/src/attributes.md
@@ -50,7 +50,7 @@ Attributes may be applied to many things in the language:
 * [Generic lifetime or type parameter][generics] accept outer attributes.
 * Expressions accept outer attributes in limited situations, see [Expression
   Attributes] for details.
-* [Function][functions], [closure]] and [function pointer]
+* [Function][functions], [closure] and [function pointer]
   parameters accept outer attributes. This includes attributes on variadic parameters
   denoted with `...` in function pointers and [external blocks][variadic functions].
 
diff --git a/src/doc/reference/src/behavior-considered-undefined.md b/src/doc/reference/src/behavior-considered-undefined.md
index 960fd37732..f3a27ad63a 100644
--- a/src/doc/reference/src/behavior-considered-undefined.md
+++ b/src/doc/reference/src/behavior-considered-undefined.md
@@ -49,7 +49,7 @@ code.
   * Invalid metadata in a wide reference, `Box`, or raw pointer:
     * `dyn Trait` metadata is invalid if it is not a pointer to a vtable for
       `Trait` that matches the actual dynamic trait the pointer or reference points to.
-    * Slice metadata is invalid if if the length is not a valid `usize`
+    * Slice metadata is invalid if the length is not a valid `usize`
       (i.e., it must not be read from uninitialized memory).
   * Non-UTF-8 byte sequences in a `str`.
   * Invalid values for a type with a custom definition of invalid values.
diff --git a/src/doc/reference/src/const_eval.md b/src/doc/reference/src/const_eval.md
index cec0145a3b..5d6c367e62 100644
--- a/src/doc/reference/src/const_eval.md
+++ b/src/doc/reference/src/const_eval.md
@@ -31,7 +31,7 @@ to be run.
     are implemented, one cannot use both short circuiting operators (`&&` and `||`) and let
     statements within the same constant.
     * [assignment expressions]
-    * [assignment operator expressions]
+    * [compound assignment expressions]
     * [expression statements]
 * [Field] expressions.
 * Index expressions, [array indexing] or [slice] with a `usize`.
@@ -63,7 +63,7 @@ A _const context_ is one of the following:
 [array indexing]:       expressions/array-expr.md#array-and-slice-indexing-expressions
 [array type length expressions]: types/array.md
 [assignment expressions]: expressions/operator-expr.md#assignment-expressions
-[assignment operator expressions]: expressions/operator-expr.md#compound-assignment-expressions
+[compound assignment expressions]: expressions/operator-expr.md#compound-assignment-expressions
 [block expressions]:    expressions/block-expr.md
 [borrow]:               expressions/operator-expr.md#borrow-operators
 [cast]:                 expressions/operator-expr.md#type-cast-expressions
@@ -73,7 +73,7 @@ A _const context_ is one of the following:
 [constants]:            items/constant-items.md
 [dereference operator]: expressions/operator-expr.md#the-dereference-operator
 [destructors]:          destructors.md
-[enum discriminants]:   items/enumerations.md#custom-discriminant-values-for-field-less-enumerations
+[enum discriminants]:   items/enumerations.md#custom-discriminant-values-for-fieldless-enumerations
 [enum variant]:         expressions/enum-variant-expr.md
 [expression statements]: statements.md#expression-statements
 [expressions]:          expressions.md
diff --git a/src/doc/reference/src/expressions/array-expr.md b/src/doc/reference/src/expressions/array-expr.md
index f31fbb8743..4d4f567e1d 100644
--- a/src/doc/reference/src/expressions/array-expr.md
+++ b/src/doc/reference/src/expressions/array-expr.md
@@ -62,7 +62,7 @@ in a _panicked state_ if it fails.
 
 ```rust,should_panic
 // lint is deny by default.
-#![warn(const_err)]
+#![warn(unconditional_panic)]
 
 ([1, 2, 3, 4])[2];        // Evaluates to 3
 
diff --git a/src/doc/reference/src/expressions/block-expr.md b/src/doc/reference/src/expressions/block-expr.md
index 33cb42109a..c35c3d6782 100644
--- a/src/doc/reference/src/expressions/block-expr.md
+++ b/src/doc/reference/src/expressions/block-expr.md
@@ -22,7 +22,7 @@ of the block.
 
 Blocks are written as `{`, then any [inner attributes], then [statements],
 then an optional expression, and finally a `}`. Statements are usually required
-to be followed a semicolon, with two exceptions. Item declaration statements do
+to be followed by a semicolon, with two exceptions. Item declaration statements do
 not need to be followed by a semicolon. Expression statements usually require
 a following semicolon except if its outer expression is a flow control
 expression. Furthermore, extra semicolons between statements are allowed, but
diff --git a/src/doc/reference/src/items/associated-items.md b/src/doc/reference/src/items/associated-items.md
index c1f82f62ec..5434c04951 100644
--- a/src/doc/reference/src/items/associated-items.md
+++ b/src/doc/reference/src/items/associated-items.md
@@ -98,24 +98,28 @@ Associated functions whose first parameter is named `self` are called *methods*
 and may be invoked using the [method call operator], for example, `x.foo()`, as
 well as the usual function call notation.
 
-If the type of the `self` parameter is specified, it is limited to one of the
-following types:
+If the type of the `self` parameter is specified, it is limited to types resolving
+to one generated by the following grammar (where `'lt` denotes some arbitrary
+lifetime):
 
-- `Self`
-- `&Self`
-- `&mut Self`
-- [`Box`]
-- [`Rc`]
-- [`Arc`]
-- [`Pin

`] where `P` is one of the above types except `Self`. +```text +P = &'lt S | &'lt mut S | Box | Rc | Arc | Pin

+S = Self | P +``` -The `Self` term can be replaced with the type being implemented. +The `Self` terminal in this grammar denotes a type resolving to the implementing type. +This can also include the contextual type alias `Self`, other type aliases, +or associated type projections resolving to the implementing type. ```rust # use std::rc::Rc; # use std::sync::Arc; # use std::pin::Pin; +// Examples of methods implemented on struct `Example`. struct Example; +type Alias = Example; +trait Trait { type Output; } +impl Trait for Example { type Output = Example; } impl Example { fn by_value(self: Self) {} fn by_ref(self: &Self) {} @@ -126,6 +130,8 @@ impl Example { fn by_pin(self: Pin<&Self>) {} fn explicit_type(self: Arc) {} fn with_lifetime<'a>(self: &'a Self) {} + fn nested<'a>(self: &mut &'a Arc>>) {} + fn via_projection(self: ::Output) {} } ``` @@ -360,4 +366,4 @@ fn main() { [function item]: ../types/function-item.md [method call operator]: ../expressions/method-call-expr.md [path]: ../paths.md -[regular function parameters]: functions.md#attributes-on-function-parameters +[regular function parameters]: functions.md#attributes-on-function-parameters diff --git a/src/doc/reference/src/items/enumerations.md b/src/doc/reference/src/items/enumerations.md index 25dfecb656..7e47955083 100644 --- a/src/doc/reference/src/items/enumerations.md +++ b/src/doc/reference/src/items/enumerations.md @@ -61,7 +61,7 @@ integer associated to it that is used to determine which variant it holds. An opaque reference to this discriminant can be obtained with the [`mem::discriminant`] function. -## Custom Discriminant Values for Field-Less Enumerations +## Custom Discriminant Values for Fieldless Enumerations If there is no data attached to *any* of the variants of an enumeration, then the discriminant can be directly chosen and accessed. diff --git a/src/doc/reference/src/items/traits.md b/src/doc/reference/src/items/traits.md index 5427dbe652..1a65c9239b 100644 --- a/src/doc/reference/src/items/traits.md +++ b/src/doc/reference/src/items/traits.md @@ -95,6 +95,98 @@ Object safe traits can be the base trait of a [trait object]. A trait is * It must not have any associated constants. * All supertraits must also be object safe. +When there isn't a `Self: Sized` bound on a method, the type of a method +receiver must be one of the following types: + +* `&Self` +* `&mut Self` +* [`Box`] +* [`Rc`] +* [`Arc`] +* [`Pin

`] where `P` is one of the types above + +```rust +# use std::rc::Rc; +# use std::sync::Arc; +# use std::pin::Pin; +// Examples of object safe methods. +trait TraitMethods { + fn by_ref(self: &Self) {} + fn by_ref_mut(self: &mut Self) {} + fn by_box(self: Box) {} + fn by_rc(self: Rc) {} + fn by_arc(self: Arc) {} + fn by_pin(self: Pin<&Self>) {} + fn with_lifetime<'a>(self: &'a Self) {} + fn nested_pin(self: Pin>) {} +} +# struct S; +# impl TraitMethods for S {} +# let t: Box = Box::new(S); +``` + +```rust,compile_fail +// This trait is object-safe, but these methods cannot be dispatched on a trait object. +trait NonDispatchable { + // Non-methods cannot be dispatched. + fn foo() where Self: Sized {} + // Self type isn't known until runtime. + fn returns(&self) -> Self where Self: Sized; + // `other` may be a different concrete type of the receiver. + fn param(&self, other: Self) where Self: Sized {} + // Generics are not compatible with vtables. + fn typed(&self, x: T) where Self: Sized {} +} + +struct S; +impl NonDispatchable for S { + fn returns(&self) -> Self where Self: Sized { S } +} +let obj: Box = Box::new(S); +obj.returns(); // ERROR: cannot call with Self return +obj.param(S); // ERROR: cannot call with Self parameter +obj.typed(1); // ERROR: cannot call with generic type +``` + +```rust,compile_fail +# use std::rc::Rc; +// Examples of non-object safe traits. +trait NotObjectSafe { + const CONST: i32 = 1; // ERROR: cannot have associated const + + fn foo() {} // ERROR: associated function without Sized + fn returns(&self) -> Self; // ERROR: Self in return type + fn typed(&self, x: T) {} // ERROR: has generic type parameters + fn nested(self: Rc>) {} // ERROR: nested receiver not yet supported +} + +struct S; +impl NotObjectSafe for S { + fn returns(&self) -> Self { S } +} +let obj: Box = Box::new(S); // ERROR +``` + +```rust,compile_fail +// Self: Sized traits are not object-safe. +trait TraitWithSize where Self: Sized {} + +struct S; +impl TraitWithSize for S {} +let obj: Box = Box::new(S); // ERROR +``` + +```rust,compile_fail +// Not object safe if `Self` is a type argument. +trait Super {} +trait WithSelf: Super where Self: Sized {} + +struct S; +impl Super for S {} +impl WithSelf for S {} +let obj: Box = Box::new(S); // ERROR: cannot use `Self` type parameter +``` + ## Supertraits **Supertraits** are traits that are required to be implemented for a type to @@ -268,3 +360,7 @@ fn main() { [trait implementation]: implementations.md#trait-implementations [`Send`]: ../special-types-and-traits.md#send [`Sync`]: ../special-types-and-traits.md#sync +[`Arc`]: ../special-types-and-traits.md#arct +[`Box`]: ../special-types-and-traits.md#boxt +[`Pin

`]: ../special-types-and-traits.md#pinp +[`Rc`]: ../special-types-and-traits.md#rct diff --git a/src/doc/reference/src/items/use-declarations.md b/src/doc/reference/src/items/use-declarations.md index 92bd780843..6de253a190 100644 --- a/src/doc/reference/src/items/use-declarations.md +++ b/src/doc/reference/src/items/use-declarations.md @@ -103,7 +103,7 @@ mod foo { } use crate::foo::example::iter; // good: foo is at crate root -// use example::iter; // bad: relative paths are not allowed without `self` +// use example::iter; // bad in 2015 edition: relative paths are not allowed without `self`; good in 2018 edition use self::baz::foobaz; // good: self refers to module 'foo' use crate::foo::bar::foobar; // good: foo is at crate root diff --git a/src/doc/reference/src/macro-ambiguity.md b/src/doc/reference/src/macro-ambiguity.md index f1dbb42850..531fbef0b6 100644 --- a/src/doc/reference/src/macro-ambiguity.md +++ b/src/doc/reference/src/macro-ambiguity.md @@ -373,5 +373,5 @@ why particular matchers are legal and others are not. * `($($e:expr)*)` : illegal, because expr NTs are not in FOLLOW(expr NT). [Macros by Example]: macros-by-example.md -[RFC 550]: https://github.com/rust-lang/rfcs/blob/master/text/0550-macro-future-proofing.html +[RFC 550]: https://github.com/rust-lang/rfcs/blob/master/text/0550-macro-future-proofing.md [tracking issue]: https://github.com/rust-lang/rust/issues/56575 diff --git a/src/doc/reference/src/paths.md b/src/doc/reference/src/paths.md index af739d7082..cdf8cc41ab 100644 --- a/src/doc/reference/src/paths.md +++ b/src/doc/reference/src/paths.md @@ -175,7 +175,8 @@ mod a { } mod b { pub fn foo() { - ::a::foo(); // call a's foo function + ::a::foo(); // call `a`'s foo function + // In Rust 2018, `::a` would be interpreted as the crate `a`. } } # fn main() {} diff --git a/src/doc/reference/src/tokens.md b/src/doc/reference/src/tokens.md index e4338f06fd..3fda6cab7a 100644 --- a/src/doc/reference/src/tokens.md +++ b/src/doc/reference/src/tokens.md @@ -579,7 +579,7 @@ usages and meanings are defined in the linked pages. | `=>` | FatArrow | [Match arms][match], [Macros] | `#` | Pound | [Attributes] | `$` | Dollar | [Macros] -| `?` | Question | [Question mark operator][question], [Questionably sized][sized] +| `?` | Question | [Question mark operator][question], [Questionably sized][sized], [Macro Kleene Matcher][macros] ## Delimiters diff --git a/src/doc/reference/src/type-layout.md b/src/doc/reference/src/type-layout.md index f6c9ca77eb..51ba859ef5 100644 --- a/src/doc/reference/src/type-layout.md +++ b/src/doc/reference/src/type-layout.md @@ -197,6 +197,19 @@ Here is this algorithm described in pseudocode. ```rust,ignore +/// Returns the amount of padding needed after `offset` to ensure that the +/// following address will be aligned to `alignment`. +fn padding_needed_for(offset: usize, alignment: usize) -> usize { + let misalignment = offset % alignment; + if misalignment > 0 { + // round up to next multiple of `alignment` + alignment - misalignment + } else { + // already a multiple of `alignment` + 0 + } +} + struct.alignment = struct.fields().map(|field| field.alignment).max(); let current_offset = 0; @@ -205,16 +218,24 @@ for field in struct.fields_in_declaration_order() { // Increase the current offset so that it's a multiple of the alignment // of this field. For the first field, this will always be zero. // The skipped bytes are called padding bytes. - current_offset += field.alignment % current_offset; + current_offset += padding_needed_for(current_offset, field.alignment); struct[field].offset = current_offset; current_offset += field.size; } -struct.size = current_offset + current_offset % struct.alignment; +struct.size = current_offset + padding_needed_for(current_offset, struct.alignment); ``` +

+ > Note: This algorithm can produce zero-sized structs. This differs from > C where structs without data still have a size of one byte. @@ -354,7 +375,7 @@ used with any other representation. [`size_of`]: ../std/mem/fn.size_of.html [`Sized`]: ../std/marker/trait.Sized.html [dynamically sized types]: dynamically-sized-types.md -[C-like enumerations]: items/enumerations.md#custom-discriminant-values-for-field-less-enumerations +[C-like enumerations]: items/enumerations.md#custom-discriminant-values-for-fieldless-enumerations [zero-variant enumerations]: items/enumerations.md#zero-variant-enums [undefined behavior]: behavior-considered-undefined.md [27060]: https://github.com/rust-lang/rust/issues/27060 @@ -363,3 +384,4 @@ used with any other representation. [`C`]: #the-c-representation [primitive representations]: #primitive-representations [`transparent`]: #the-transparent-representation +[`Layout`]: ../std/alloc/struct.Layout.html diff --git a/src/doc/reference/src/types/pointer.md b/src/doc/reference/src/types/pointer.md index 8ed3fa8b90..de97815d20 100644 --- a/src/doc/reference/src/types/pointer.md +++ b/src/doc/reference/src/types/pointer.md @@ -3,12 +3,14 @@ All pointers in Rust are explicit first-class values. They can be moved or copied, stored into data structs, and returned from functions. -## Shared references (`&`) +## References (`&` and `&mut`) > **Syntax**\ > _ReferenceType_ :\ >    `&` [_Lifetime_]? `mut`? [_TypeNoBounds_] +### Shared references (`&`) + These point to memory _owned by some other value_. When a shared reference to a value is created it prevents direct mutation of the value. [Interior mutability] provides an exception for this in certain circumstances. As the @@ -19,7 +21,7 @@ only copying the pointer itself, that is, pointers are `Copy`. Releasing a reference has no effect on the value it points to, but referencing of a [temporary value] will keep it alive during the scope of the reference itself. -## Mutable references (`&mut`) +### Mutable references (`&mut`) These also point to memory owned by some other value. A mutable reference type is written `&mut type` or `&'a mut type`. A mutable reference (that hasn't been diff --git a/src/doc/reference/src/types/trait-object.md b/src/doc/reference/src/types/trait-object.md index d514e4a2d6..7e37e41ccf 100644 --- a/src/doc/reference/src/types/trait-object.md +++ b/src/doc/reference/src/types/trait-object.md @@ -97,7 +97,7 @@ need to be expressed as part of the trait object. This lifetime is written as inferred with a sensible choice. [_TraitBound_]: ../trait-bounds.md -[_TypeParamBounds_]: ../types.md#type-expressions +[_TypeParamBounds_]: ../trait-bounds.md [auto traits]: ../special-types-and-traits.md#auto-traits [defaults]: ../lifetime-elision.md#default-trait-object-lifetimes [dynamically sized types]: ../dynamically-sized-types.md diff --git a/src/doc/robots.txt b/src/doc/robots.txt index 61ee12739f..d119cc4647 100644 --- a/src/doc/robots.txt +++ b/src/doc/robots.txt @@ -1,4 +1,3 @@ -# NB: This file is not automatically deployed. After changes, it needs to be uploaded manually to doc.rust-lang.org User-agent: * Disallow: /0.3/ Disallow: /0.4/ diff --git a/src/doc/rust-by-example/src/conversion/from_into.md b/src/doc/rust-by-example/src/conversion/from_into.md index 9be8bc24ad..266d10f285 100644 --- a/src/doc/rust-by-example/src/conversion/from_into.md +++ b/src/doc/rust-by-example/src/conversion/from_into.md @@ -43,8 +43,8 @@ fn main() { ## `Into` The [`Into`] trait is simply the reciprocal of the `From` trait. That is, if you -have implemented the `From` trait for your type you get the `Into` -implementation for free. +have implemented the `From` trait for your type, `Into` will call it when +necessary. Using the `Into` trait will typically require specification of the type to convert into as the compiler is unable to determine this most of the time. diff --git a/src/doc/rust-by-example/src/error/multiple_error_types/reenter_question_mark.md b/src/doc/rust-by-example/src/error/multiple_error_types/reenter_question_mark.md index bf93e8a42d..a94c0f8e5e 100644 --- a/src/doc/rust-by-example/src/error/multiple_error_types/reenter_question_mark.md +++ b/src/doc/rust-by-example/src/error/multiple_error_types/reenter_question_mark.md @@ -26,8 +26,8 @@ Here, we rewrite the previous example using `?`. As a result, the use std::error; use std::fmt; -// Change the alias to `Box`. -type Result = std::result::Result>; +// Change the alias to `Box`. +type Result = std::result::Result>; #[derive(Debug)] struct EmptyVec; diff --git a/src/doc/rust-by-example/src/flow_control/for.md b/src/doc/rust-by-example/src/flow_control/for.md index 591b86637c..99e6458493 100644 --- a/src/doc/rust-by-example/src/flow_control/for.md +++ b/src/doc/rust-by-example/src/flow_control/for.md @@ -49,14 +49,13 @@ fn main() { ## for and iterators The `for in` construct is able to interact with an `Iterator` in several ways. -As discussed in with the [Iterator][iter] trait, if not specified, the `for` -loop will apply the `into_iter` function on the collection provided to convert -the collection into an iterator. This is not the only means to convert a -collection into an iterator however, the other functions available include -`iter` and `iter_mut`. - -These 3 functions will return different views of the data within your -collection. +As discussed in the section on the [Iterator][iter] trait, by default the `for` +loop will apply the `into_iter` function to the collection. However, this is +not the only means of converting collections into iterators. + +`into_iter`, `iter` and `iter_mut` all handle the conversion of a collection +into an iterator in different ways, by providing different views on the data +within. * `iter` - This borrows each element of the collection through each iteration. Thus leaving the collection untouched and available for reuse after the loop. diff --git a/src/doc/rust-by-example/src/flow_control/if_let.md b/src/doc/rust-by-example/src/flow_control/if_let.md index 22bdde8d1b..3742b6f683 100644 --- a/src/doc/rust-by-example/src/flow_control/if_let.md +++ b/src/doc/rust-by-example/src/flow_control/if_let.md @@ -99,13 +99,13 @@ fn main() { } ``` -Another benefit: `if let` allows to match enum non-parameterized variants, even if the enum doesn't `#[derive(PartialEq)]`, neither we implement `PartialEq` for it. In such case, classic `if Foo::Bar==a` fails, because instances of such enum are not comparable for equality. However, `if let` works. +Another benefit is that `if let` allows us to match non-parameterized enum variants. This is true even in cases where the enum doesn't implement or derive `PartialEq`. In such cases `if Foo::Bar == a` would fail to compile, because instances of the enum cannot be equated, however `if let` will continue to work. Would you like a challenge? Fix the following example to use `if let`: ```rust,editable,ignore,mdbook-runnable -// This enum purposely doesn't #[derive(PartialEq)], -// neither we implement PartialEq for it. That's why comparing Foo::Bar==a fails below. +// This enum purposely neither implements nor derives PartialEq. +// That is why comparing Foo::Bar == a fails below. enum Foo {Bar} fn main() { diff --git a/src/doc/rust-by-example/src/mod/visibility.md b/src/doc/rust-by-example/src/mod/visibility.md index 84840e43de..173122c72a 100644 --- a/src/doc/rust-by-example/src/mod/visibility.md +++ b/src/doc/rust-by-example/src/mod/visibility.md @@ -101,7 +101,7 @@ fn main() { // pub(crate) items can be called from anywhere in the same crate my_mod::public_function_in_crate(); - // pub(in path) items can only be called from within the mode specified + // pub(in path) items can only be called from within the module specified // Error! function `public_function_in_my_mod` is private //my_mod::nested::public_function_in_my_mod(); // TODO ^ Try uncommenting this line diff --git a/src/doc/rustc-guide/.editorconfig b/src/doc/rustc-dev-guide/.editorconfig similarity index 100% rename from src/doc/rustc-guide/.editorconfig rename to src/doc/rustc-dev-guide/.editorconfig diff --git a/src/doc/rustc-guide/.travis.yml b/src/doc/rustc-dev-guide/.travis.yml similarity index 89% rename from src/doc/rustc-guide/.travis.yml rename to src/doc/rustc-dev-guide/.travis.yml index 6ee759d4cc..e88ae40b2a 100644 --- a/src/doc/rustc-guide/.travis.yml +++ b/src/doc/rustc-dev-guide/.travis.yml @@ -10,7 +10,8 @@ before_install: - MAX_LINE_LENGTH=100 bash ci/check_line_lengths.sh src/**/*.md install: - source ~/.cargo/env || true -- bash -x ci/install.sh +- cargo install mdbook --version 0.3.4 +- cargo install mdbook-linkcheck --version 0.5.0 script: - mdbook build notifications: @@ -24,5 +25,6 @@ deploy: skip-cleanup: true github-token: $GITHUB_TOKEN local-dir: book/html + fqdn: rustc-dev-guide.rust-lang.org on: branch: master diff --git a/src/doc/rustc-dev-guide/CNAME b/src/doc/rustc-dev-guide/CNAME new file mode 100644 index 0000000000..a59cd86cd4 --- /dev/null +++ b/src/doc/rustc-dev-guide/CNAME @@ -0,0 +1 @@ +rustc-dev-guide.rust-lang.org diff --git a/src/doc/rustc-guide/CODE_OF_CONDUCT.md b/src/doc/rustc-dev-guide/CODE_OF_CONDUCT.md similarity index 100% rename from src/doc/rustc-guide/CODE_OF_CONDUCT.md rename to src/doc/rustc-dev-guide/CODE_OF_CONDUCT.md diff --git a/src/doc/rustc-guide/LICENSE-APACHE b/src/doc/rustc-dev-guide/LICENSE-APACHE similarity index 100% rename from src/doc/rustc-guide/LICENSE-APACHE rename to src/doc/rustc-dev-guide/LICENSE-APACHE diff --git a/src/doc/rustc-guide/LICENSE-MIT b/src/doc/rustc-dev-guide/LICENSE-MIT similarity index 100% rename from src/doc/rustc-guide/LICENSE-MIT rename to src/doc/rustc-dev-guide/LICENSE-MIT diff --git a/src/doc/rustc-dev-guide/README.md b/src/doc/rustc-dev-guide/README.md new file mode 100644 index 0000000000..0989718623 --- /dev/null +++ b/src/doc/rustc-dev-guide/README.md @@ -0,0 +1,85 @@ +![Travis CI badge](https://api.travis-ci.com/rust-lang/rustc-dev-guide.svg?branch=master) + + +This is a collaborative effort to build a guide that explains how rustc +works. The aim of the guide is to help new contributors get oriented +to rustc, as well as to help more experienced folks in figuring out +some new part of the compiler that they haven't worked on before. + +[You can read the latest version of the guide here.](https://rustc-dev-guide.rust-lang.org/) + +You may also find the rustdocs [for the compiler itself][rustdocs] useful. + +[rustdocs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ + +### Contributing to the guide + +The guide is useful today, but it has a lot of work still go. + +If you'd like to help improve the guide, we'd love to have you! You can find +plenty of issues on the [issue +tracker](https://github.com/rust-lang/rustc-dev-guide/issues). Just post a +comment on the issue you would like to work on to make sure that we don't +accidentally duplicate work. If you think something is missing, please open an +issue about it! + +**In general, if you don't know how the compiler works, that is not a +problem!** In that case, what we will do is to schedule a bit of time +for you to talk with someone who **does** know the code, or who wants +to pair with you and figure it out. Then you can work on writing up +what you learned. + +In general, when writing about a particular part of the compiler's code, we +recommend that you link to the relevant parts of the [rustc +rustdocs][rustdocs]. + +To help prevent accidentally introducing broken links, we use the +`mdbook-linkcheck`. If installed on your machine `mdbook` will automatically +invoke this link checker, otherwise it will emit a warning saying it couldn't +be found. + +```bash +> cargo install mdbook-linkcheck +``` + +You will need `mdbook` version `>= 0.3.5` and `mdbook-linkcheck` version `>= 0.5`. +`linkcheck` will be run automatically when you run `mdbook build`. + +## How to fix toolstate failures + +1. You will get a ping from the toolstate commit. e.g. https://github.com/rust-lang-nursery/rust-toolstate/commit/8ffa0e4c30ac9ba8546b7046e5c4ccc2b96ebdd4 + +2. The commit contains a link to the PR that caused the breakage. e.g. https://github.com/rust-lang/rust/pull/64321 + +3. If you go to that PR's thread, there is a post from bors with a link to the CI status: https://github.com/rust-lang/rust/pull/64321#issuecomment-529763807 + +4. Follow the check-azure link to get to the Azure website for that build: https://dev.azure.com/rust-lang/e71b0ddf-dd27-435a-873c-e30f86eea377/_build/results?buildId=7780 + +5. There will be approximately 1 billion different jobs for the build. They are for different configurations and platforms. The rustc-dev-guide build only runs on the Linux x86_64-gnu-tools job. So click on that job in the list, which is about 60% down in the list. + +6. Click the Run build step in the job to get the console log for the step. + +7. Click on the log and Ctrl-f to get a search box in the log + +8. Search for rustc-dev-guide. This gets you to the place where the links are checked. It is usually ~11K lines into the log + +9. Look at the links in the log near that point in the log + +10. Fix those links in the rustc-dev-guide (by making a PR in the rustc-dev-guide repo) + +11. Make a PR on the rust-lang/rust repo to update the rustc-dev-guide git submodule in src/docs/rustc-dev-guide. +To make a PR, the following steps are useful. + +```bash +# Assuming you already cloned the rust-lang/rust repo and you're in the correct directory +git submodule update --remote src/doc/rustc-dev-guide +git add -u +git commit -m "Update rustc-dev-guide" +# Note that you can use -i, which is short for --incremental, in the following command +./x.py test --incremental --stage 1 src/doc/rustc-dev-guide # This is optional and should succeed anyway +# Open a PR in rust-lang/rust +``` + +12. Wait for PR to merge + +Voilà! diff --git a/src/doc/rustc-dev-guide/book.toml b/src/doc/rustc-dev-guide/book.toml new file mode 100644 index 0000000000..3d90479cb2 --- /dev/null +++ b/src/doc/rustc-dev-guide/book.toml @@ -0,0 +1,20 @@ +[book] +title = "Guide to Rustc Development" +author = "Rustc developers" +description = "A guide to developing rustc" + +[build] +create-missing = false + +[output.html] +git-repository-url = "https://github.com/rust-lang/rustc-dev-guide" + +[output.html.fold] +enable = true +level = 1 + +[output.linkcheck] +follow-web-links = true +exclude = [ "crates\\.io", "gcc\\.godbolt\\.org", "youtube\\.com", "youtu\\.be", "dl\\.acm\\.org", "cs\\.bgu\\.ac\\.il" ] +cache-timeout = 172800 +warning-policy = "error" diff --git a/src/doc/rustc-guide/ci/check_line_lengths.sh b/src/doc/rustc-dev-guide/ci/check_line_lengths.sh similarity index 100% rename from src/doc/rustc-guide/ci/check_line_lengths.sh rename to src/doc/rustc-dev-guide/ci/check_line_lengths.sh diff --git a/src/doc/rustc-guide/src/SUMMARY.md b/src/doc/rustc-dev-guide/src/SUMMARY.md similarity index 96% rename from src/doc/rustc-guide/src/SUMMARY.md rename to src/doc/rustc-dev-guide/src/SUMMARY.md index 125e20cf6f..ae1ea0b2e0 100644 --- a/src/doc/rustc-guide/src/SUMMARY.md +++ b/src/doc/rustc-dev-guide/src/SUMMARY.md @@ -30,6 +30,7 @@ - [`LintStore`](./diagnostics/lintstore.md) - [Diagnostic Codes](./diagnostics/diagnostic-codes.md) - [ICE-breaker teams](ice-breaker/about.md) + - ["Cleanup Crew" ICE-breakers](ice-breaker/cleanup-crew.md) - [LLVM ICE-breakers](ice-breaker/llvm.md) - [Part 2: How rustc works](./part-2-intro.md) - [High-level overview of the compiler source](./high-level-overview.md) @@ -42,6 +43,7 @@ - [Debugging and Testing](./incrcomp-debugging.md) - [Profiling Queries](./queries/profiling.md) - [Salsa](./salsa.md) + - [Memory Management in Rustc](./memory.md) - [Lexing and Parsing](./the-parser.md) - [`#[test]` Implementation](./test-implementation.md) - [Panic Implementation](./panic-implementation.md) @@ -52,6 +54,8 @@ - [Debugging](./hir-debugging.md) - [Closure expansion](./closure.md) - [The `ty` module: representing types](./ty.md) + - [Generics and substitutions](./generics.md) + - [`TypeFolder` and `TypeFoldable`](./ty-fold.md) - [Generic arguments](./generic_arguments.md) - [Type inference](./type-inference.md) - [Trait solving (old-style)](./traits/resolution.md) diff --git a/src/doc/rustc-guide/src/about-this-guide.md b/src/doc/rustc-dev-guide/src/about-this-guide.md similarity index 95% rename from src/doc/rustc-guide/src/about-this-guide.md rename to src/doc/rustc-dev-guide/src/about-this-guide.md index 48ea4dce63..0519099b31 100644 --- a/src/doc/rustc-guide/src/about-this-guide.md +++ b/src/doc/rustc-dev-guide/src/about-this-guide.md @@ -25,7 +25,7 @@ You might also find the following sites useful: - [compiler-team] -- the home-base for the rust compiler team, with description of the team procedures, active working groups, and the team calendar. -[GitHub repository]: https://github.com/rust-lang/rustc-guide/ +[GitHub repository]: https://github.com/rust-lang/rustc-dev-guide/ [Rustc API docs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ [Forge]: https://forge.rust-lang.org/ [compiler-team]: https://github.com/rust-lang/compiler-team/ diff --git a/src/doc/rustc-guide/src/appendix/background.md b/src/doc/rustc-dev-guide/src/appendix/background.md similarity index 100% rename from src/doc/rustc-guide/src/appendix/background.md rename to src/doc/rustc-dev-guide/src/appendix/background.md diff --git a/src/doc/rustc-guide/src/appendix/bibliography.md b/src/doc/rustc-dev-guide/src/appendix/bibliography.md similarity index 100% rename from src/doc/rustc-guide/src/appendix/bibliography.md rename to src/doc/rustc-dev-guide/src/appendix/bibliography.md diff --git a/src/doc/rustc-guide/src/appendix/code-index.md b/src/doc/rustc-dev-guide/src/appendix/code-index.md similarity index 86% rename from src/doc/rustc-guide/src/appendix/code-index.md rename to src/doc/rustc-dev-guide/src/appendix/code-index.md index 39e16c1cba..0321da195d 100644 --- a/src/doc/rustc-guide/src/appendix/code-index.md +++ b/src/doc/rustc-dev-guide/src/appendix/code-index.md @@ -8,16 +8,16 @@ Item | Kind | Short description | Chapter | ----------------|----------|-----------------------------|--------------------|------------------- `BodyId` | struct | One of four types of HIR node identifiers | [Identifiers in the HIR] | [src/librustc_hir/hir.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/struct.BodyId.html) `Compiler` | struct | Represents a compiler session and can be used to drive a compilation. | [The Rustc Driver and Interface] | [src/librustc_interface/interface.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_interface/interface/struct.Compiler.html) -`ast::Crate` | struct | A syntax-level representation of a parsed crate | [The parser] | [src/libsyntax/ast.rs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/struct.Crate.html) +`ast::Crate` | struct | A syntax-level representation of a parsed crate | [The parser] | [src/librustc_ast/ast.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/struct.Crate.html) `rustc_hir::Crate` | struct | A more abstract, compiler-friendly form of a crate's AST | [The Hir] | [src/librustc_hir/hir.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/struct.Crate.html) `DefId` | struct | One of four types of HIR node identifiers | [Identifiers in the HIR] | [src/librustc_hir/def_id.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/def_id/struct.DefId.html) `DiagnosticBuilder` | struct | A struct for building up compiler diagnostics, such as errors or lints | [Emitting Diagnostics] | [src/librustc_errors/diagnostic_builder.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/struct.DiagnosticBuilder.html) `DocContext` | struct | A state container used by rustdoc when crawling through a crate to gather its documentation | [Rustdoc] | [src/librustdoc/core.rs](https://github.com/rust-lang/rust/blob/master/src/librustdoc/core.rs) `HirId` | struct | One of four types of HIR node identifiers | [Identifiers in the HIR] | [src/librustc_hir/hir_id.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir_id/struct.HirId.html) -`NodeId` | struct | One of four types of HIR node identifiers. Being phased out | [Identifiers in the HIR] | [src/libsyntax/ast.rs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/struct.NodeId.html) -`P` | struct | An owned immutable smart pointer. By contrast, `&T` is not owned, and `Box` is not immutable. | None | [src/syntax/ptr.rs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ptr/struct.P.html) +`NodeId` | struct | One of four types of HIR node identifiers. Being phased out | [Identifiers in the HIR] | [src/librustc_ast/ast.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/node_id/struct.NodeId.html) +`P` | struct | An owned immutable smart pointer. By contrast, `&T` is not owned, and `Box` is not immutable. | None | [src/librustc_ast/ptr.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ptr/struct.P.html) `ParamEnv` | struct | Information about generic parameters or `Self`, useful for working with associated or generic items | [Parameter Environment] | [src/librustc/ty/mod.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.ParamEnv.html) -`ParseSess` | struct | This struct contains information about a parsing session | [The parser] | [src/libsyntax/parse/mod.rs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/sess/struct.ParseSess.html) +`ParseSess` | struct | This struct contains information about a parsing session | [The parser] | [src/librustc_session/parse/parse.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/parse/struct.ParseSess.html) `Query` | struct | Represents the result of query to the `Compiler` interface and allows stealing, borrowing, and returning the results of compiler passes. | [The Rustc Driver and Interface] | [src/librustc_interface/queries.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_interface/queries/struct.Query.html) `Rib` | struct | Represents a single scope of names | [Name resolution] | [src/librustc_resolve/lib.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_resolve/late/struct.Rib.html) `Session` | struct | The data associated with a compilation session | [The parser], [The Rustc Driver and Interface] | [src/librustc/session/mod.html](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/struct.Session.html) @@ -25,7 +25,7 @@ Item | Kind | Short description | Chapter | `SourceMap` | struct | Maps AST nodes to their source code. It is composed of `SourceFile`s. Was previously called CodeMap | [The parser] | [src/librustc_span/source_map.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/source_map/struct.SourceMap.html) `Span` | struct | A location in the user's source code, used for error reporting primarily | [Emitting Diagnostics] | [src/librustc_span/span_encoding.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html) `StringReader` | struct | This is the lexer used during parsing. It consumes characters from the raw source code being compiled and produces a series of tokens for use by the rest of the parser | [The parser] | [src/librustc_parse/lexer/mod.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse/lexer/struct.StringReader.html) -`syntax::token_stream::TokenStream` | struct | An abstract sequence of tokens, organized into `TokenTree`s | [The parser], [Macro expansion] | [src/libsyntax/tokenstream.rs](https://doc.rust-lang.org/nightly/nightly-rustc/syntax/tokenstream/struct.TokenStream.html) +`rustc_ast::token_stream::TokenStream` | struct | An abstract sequence of tokens, organized into `TokenTree`s | [The parser], [Macro expansion] | [src/librustc_ast/tokenstream.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/tokenstream/struct.TokenStream.html) `TraitDef` | struct | This struct contains a trait's definition with type information | [The `ty` modules] | [src/librustc/ty/trait_def.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/trait_def/struct.TraitDef.html) `TraitRef` | struct | The combination of a trait and its input types (e.g. `P0: Trait`) | [Trait Solving: Goals and Clauses], [Trait Solving: Lowering impls] | [src/librustc/ty/sty.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TraitRef.html) `Ty<'tcx>` | struct | This is the internal representation of a type used for type checking | [Type checking] | [src/librustc/ty/mod.rs](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/type.Ty.html) diff --git a/src/doc/rustc-dev-guide/src/appendix/compiler-lecture.md b/src/doc/rustc-dev-guide/src/appendix/compiler-lecture.md new file mode 100644 index 0000000000..bbeb52aa3a --- /dev/null +++ b/src/doc/rustc-dev-guide/src/appendix/compiler-lecture.md @@ -0,0 +1,27 @@ +# Compiler Lecture Series + +These are videos where various experts explain different parts of the compiler: + +- [Tom Tromey discusses debugging support in rustc](https://www.youtube.com/watch?v=elBxMRSNYr4) +- [How Salsa Works (2019.01)](https://www.youtube.com/watch?v=_muY4HjSqVw) +- [Salsa In More Depth (2019.01)](https://www.youtube.com/watch?v=i_IhACacPRY) +- [RLS 2.0, Salsa, and Name Resolution](https://www.youtube.com/watch?v=Xr-rBqLr-G4) +- [Cranelift](https://www.youtube.com/watch?v=9OIA7DTFQWU) +- [Rust analyzer guide](https://www.youtube.com/watch?v=ANKBNiSWyfc) +- [Rust analyzer syntax trees](https://www.youtube.com/watch?v=DGAuLWdCCAI) +- [rust-analyzer type-checker overview by flodiebold](https://www.youtube.com/watch?v=Lmp3P9WNL8o) +- [oli-obk on miri and constant evaluation](https://www.youtube.com/watch?v=5Pm2C1YXrvM) +- [Polonius-rustc walkthrough](https://www.youtube.com/watch?v=i5KdU0ieb_A) +- [rustc-chalk integration overview](https://www.youtube.com/watch?v=MBWtbDifPeU) +- [Coherence in Chalk by Sunjay Varma - Bay Area Rust Meetup](https://www.youtube.com/watch?v=rZqS4bLPL24) +- [How the chalk-engine crate works](https://www.youtube.com/watch?v=Ny2928cGDoM) +- [How the chalk-engine crate works 2](https://www.youtube.com/watch?v=hmV66tB79LM) +- [RFC #2229 Disjoint Field Capture plan](https://www.youtube.com/watch?v=UTXOptVMuIc) +- [closures and upvar capture](https://www.youtube.com/watch?v=fMopdkn5-Xw) +- [blitzerr closure upvar tys](https://www.youtube.com/watch?v=pLmVhSB-z4s) +- [Convert Closure Upvar Representation to Tuples with blitzerr](https://www.youtube.com/watch?v=2QCuNtISoYc) +- [async-await implementation plans](https://www.youtube.com/watch?v=xe2_whJWBC0) +- [async-await region inferencer](https://www.youtube.com/watch?v=hlOxfkUDLPQ) +- [Universes and Lifetimes](https://www.youtube.com/watch?v=iV1Z0xYXkck) +- [Representing types in rustc](https://www.youtube.com/watch?v=c01TsOsr3-c) +- [Polonius WG: Initialization and move tracking](https://www.youtube.com/watch?v=ilv9V-328HI) diff --git a/src/doc/rustc-dev-guide/src/appendix/glossary.md b/src/doc/rustc-dev-guide/src/appendix/glossary.md new file mode 100644 index 0000000000..f5274a8fc6 --- /dev/null +++ b/src/doc/rustc-dev-guide/src/appendix/glossary.md @@ -0,0 +1,88 @@ +# Appendix C: Glossary + +The compiler uses a number of...idiosyncratic abbreviations and things. This +glossary attempts to list them and give you a few pointers for understanding +them better. + +Term | Meaning +------------------------|-------- +arena/arena allocation | an _arena_ is a large memory buffer from which other memory allocations are made. This style of allocation is called _area allocation_. See [this chapter](../memory.md) for more info. +AST | the abstract syntax tree produced by the `rustc_ast` crate; reflects user syntax very closely. +binder | a "binder" is a place where a variable or type is declared; for example, the `` is a binder for the generic type parameter `T` in `fn foo(..)`, and \|`a`\|` ...` is a binder for the parameter `a`. See [the background chapter for more](./background.html#free-vs-bound) +bound variable | a "bound variable" is one that is declared within an expression/term. For example, the variable `a` is bound within the closure expression \|`a`\|` a * 2`. See [the background chapter for more](./background.html#free-vs-bound) +codegen | the code to translate MIR into LLVM IR. +codegen unit | when we produce LLVM IR, we group the Rust code into a number of codegen units (sometimes abbreviated as CGUs). Each of these units is processed by LLVM independently from one another, enabling parallelism. They are also the unit of incremental re-use. +completeness | completeness is a technical term in type theory. Completeness means that every type-safe program also type-checks. Having both soundness and completeness is very hard, and usually soundness is more important. (see "soundness"). +control-flow graph | a representation of the control-flow of a program; see [the background chapter for more](./background.html#cfg) +CTFE | Compile-Time Function Evaluation. This is the ability of the compiler to evaluate `const fn`s at compile time. This is part of the compiler's constant evaluation system. ([see more](../const-eval.html)) +cx | we tend to use "cx" as an abbreviation for context. See also `tcx`, `infcx`, etc. +DAG | a directed acyclic graph is used during compilation to keep track of dependencies between queries. ([see more](../queries/incremental-compilation.html)) +data-flow analysis | a static analysis that figures out what properties are true at each point in the control-flow of a program; see [the background chapter for more](./background.html#dataflow) +DefId | an index identifying a definition (see `librustc/hir/def_id.rs`). Uniquely identifies a `DefPath`. +Double pointer | a pointer with additional metadata. See "fat pointer" for more. +drop glue | (internal) compiler-generated instructions that handle calling the destructors (`Drop`) for data types. +DST | Dynamically-Sized Type. A type for which the compiler cannot statically know the size in memory (e.g. `str` or `[u8]`). Such types don't implement `Sized` and cannot be allocated on the stack. They can only occur as the last field in a struct. They can only be used behind a pointer (e.g. `&str` or `&[u8]`). +early-bound lifetime | a lifetime region that is substituted at its definition site. Bound in an item's `Generics` and substituted using a `Substs`. Contrast with **late-bound lifetime**. ([see more](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.RegionKind.html#bound-regions)) +empty type | see "uninhabited type". +Fat pointer | a two word value carrying the address of some value, along with some further information necessary to put the value to use. Rust includes two kinds of "fat pointers": references to slices, and trait objects. A reference to a slice carries the starting address of the slice and its length. A trait object carries a value's address and a pointer to the trait's implementation appropriate to that value. "Fat pointers" are also known as "wide pointers", and "double pointers". +free variable | a "free variable" is one that is not bound within an expression or term; see [the background chapter for more](./background.html#free-vs-bound) +generics | the set of generic type parameters defined on a type or item +HIR | the High-level IR, created by lowering and desugaring the AST ([see more](../hir.html)) +HirId | identifies a particular node in the HIR by combining a def-id with an "intra-definition offset". +HIR Map | The HIR map, accessible via tcx.hir, allows you to quickly navigate the HIR and convert between various forms of identifiers. +ICE | internal compiler error. When the compiler crashes. +ICH | incremental compilation hash. ICHs are used as fingerprints for things such as HIR and crate metadata, to check if changes have been made. This is useful in incremental compilation to see if part of a crate has changed and should be recompiled. +inference variable | when doing type or region inference, an "inference variable" is a kind of special type/region that represents what you are trying to infer. Think of X in algebra. For example, if we are trying to infer the type of a variable in a program, we create an inference variable to represent that unknown type. +infcx | the inference context (see `librustc/infer`) +intern | interning refers to storing certain frequently-used constant data, such as strings, and then referring to the data by an identifier (e.g. a `Symbol`) rather than the data itself, to reduce memory usage and number of allocations. See [this chapter](../memory.md) for more info. +IR | Intermediate Representation. A general term in compilers. During compilation, the code is transformed from raw source (ASCII text) to various IRs. In Rust, these are primarily HIR, MIR, and LLVM IR. Each IR is well-suited for some set of computations. For example, MIR is well-suited for the borrow checker, and LLVM IR is well-suited for codegen because LLVM accepts it. +IRLO | `IRLO` or `irlo` is sometimes used as an abbreviation for [internals.rust-lang.org](https://internals.rust-lang.org). +item | a kind of "definition" in the language, such as a static, const, use statement, module, struct, etc. Concretely, this corresponds to the `Item` type. +lang item | items that represent concepts intrinsic to the language itself, such as special built-in traits like `Sync` and `Send`; or traits representing operations such as `Add`; or functions that are called by the compiler. ([see more](https://doc.rust-lang.org/1.9.0/book/lang-items.html)) +late-bound lifetime | a lifetime region that is substituted at its call site. Bound in a HRTB and substituted by specific functions in the compiler, such as `liberate_late_bound_regions`. Contrast with **early-bound lifetime**. ([see more](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.RegionKind.html#bound-regions)) +local crate | the crate currently being compiled. +LTO | Link-Time Optimizations. A set of optimizations offered by LLVM that occur just before the final binary is linked. These include optimizations like removing functions that are never used in the final program, for example. _ThinLTO_ is a variant of LTO that aims to be a bit more scalable and efficient, but possibly sacrifices some optimizations. You may also read issues in the Rust repo about "FatLTO", which is the loving nickname given to non-Thin LTO. LLVM documentation: [here][lto] and [here][thinlto] +[LLVM] | (actually not an acronym :P) an open-source compiler backend. It accepts LLVM IR and outputs native binaries. Various languages (e.g. Rust) can then implement a compiler front-end that output LLVM IR and use LLVM to compile to all the platforms LLVM supports. +memoize | memoization is the process of storing the results of (pure) computations (such as pure function calls) to avoid having to repeat them in the future. This is typically a trade-off between execution speed and memory usage. +MIR | the Mid-level IR that is created after type-checking for use by borrowck and codegen ([see more](../mir/index.html)) +miri | an interpreter for MIR used for constant evaluation ([see more](../miri.html)) +monomorphize | Monomorphization is the process of taking generic implementations of types and functions and instantiating them with concrete types. For example, in the code we might have `Vec`, but in the final executable, we will have a copy of the `Vec` code for every concrete type used in the program (e.g. a copy for `Vec`, a copy for `Vec`, etc). +normalize | a general term for converting to a more canonical form, but in the case of rustc typically refers to [associated type normalization](../traits/associated-types.html#normalize) +newtype | a "newtype" is a wrapper around some other type (e.g., `struct Foo(T)` is a "newtype" for `T`). This is commonly used in Rust to give a stronger type for indices. +NLL | [non-lexical lifetimes](../borrow_check/region_inference.html), an extension to Rust's borrowing system to make it be based on the control-flow graph. +node-id or NodeId | an index identifying a particular node in the AST or HIR; gradually being phased out and replaced with `HirId`. +obligation | something that must be proven by the trait system ([see more](../traits/resolution.html)) +point | used in the NLL analysis to refer to some particular location in the MIR; typically used to refer to a node in the control-flow graph. +projection | a general term for a "relative path", e.g. `x.f` is a "field projection", and `T::Item` is an ["associated type projection"](../traits/goals-and-clauses.html#trait-ref) +promoted constants | constants extracted from a function and lifted to static scope; see [this section](../mir/index.html#promoted) for more details. +provider | the function that executes a query ([see more](../query.html)) +quantified | in math or logic, existential and universal quantification are used to ask questions like "is there any type T for which is true?" or "is this true for all types T?"; see [the background chapter for more](./background.html#quantified) +query | perhaps some sub-computation during compilation ([see more](../query.html)) +region | another term for "lifetime" often used in the literature and in the borrow checker. +rib | a data structure in the name resolver that keeps track of a single scope for names. ([see more](../name-resolution.html)) +sess | the compiler session, which stores global data used throughout compilation +side tables | because the AST and HIR are immutable once created, we often carry extra information about them in the form of hashtables, indexed by the id of a particular node. +sigil | like a keyword but composed entirely of non-alphanumeric tokens. For example, `&` is a sigil for references. +placeholder | **NOTE: skolemization is deprecated by placeholder** a way of handling subtyping around "for-all" types (e.g., `for<'a> fn(&'a u32)`) as well as solving higher-ranked trait bounds (e.g., `for<'a> T: Trait<'a>`). See [the chapter on placeholder and universes](../borrow_check/region_inference/placeholders_and_universes.md) for more details. +soundness | soundness is a technical term in type theory. Roughly, if a type system is sound, then if a program type-checks, it is type-safe; i.e. I can never (in safe rust) force a value into a variable of the wrong type. (see "completeness"). +span | a location in the user's source code, used for error reporting primarily. These are like a file-name/line-number/column tuple on steroids: they carry a start/end point, and also track macro expansions and compiler desugaring. All while being packed into a few bytes (really, it's an index into a table). See the Span datatype for more. +substs | the substitutions for a given generic type or item (e.g. the `i32`, `u32` in `HashMap`) +tcx | the "typing context", main data structure of the compiler ([see more](../ty.html)) +'tcx | the lifetime of the allocation arena ([see more](../ty.html)) +trait reference | the name of a trait along with a suitable set of input type/lifetimes ([see more](../traits/goals-and-clauses.html#trait-ref)) +token | the smallest unit of parsing. Tokens are produced after lexing ([see more](../the-parser.html)). +[TLS] | Thread-Local Storage. Variables may be defined so that each thread has its own copy (rather than all threads sharing the variable). This has some interactions with LLVM. Not all platforms support TLS. +trans | the code to translate MIR into LLVM IR. Renamed to codegen. +trait reference | a trait and values for its type parameters ([see more](../ty.html)). +ty | the internal representation of a type ([see more](../ty.html)). +UFCS | Universal Function Call Syntax. An unambiguous syntax for calling a method ([see more](../type-checking.html)). +uninhabited type | a type which has _no_ values. This is not the same as a ZST, which has exactly 1 value. An example of an uninhabited type is `enum Foo {}`, which has no variants, and so, can never be created. The compiler can treat code that deals with uninhabited types as dead code, since there is no such value to be manipulated. `!` (the never type) is an uninhabited type. Uninhabited types are also called "empty types". +upvar | a variable captured by a closure from outside the closure. +variance | variance determines how changes to a generic type/lifetime parameter affect subtyping; for example, if `T` is a subtype of `U`, then `Vec` is a subtype `Vec` because `Vec` is *covariant* in its generic parameter. See [the background chapter](./background.html#variance) for a more general explanation. See the [variance chapter](../variance.html) for an explanation of how type checking handles variance. +Wide pointer | a pointer with additional metadata. See "fat pointer" for more. +ZST | Zero-Sized Type. A type whose values have size 0 bytes. Since `2^0 = 1`, such types can have exactly one value. For example, `()` (unit) is a ZST. `struct Foo;` is also a ZST. The compiler can do some nice optimizations around ZSTs. + +[LLVM]: https://llvm.org/ +[lto]: https://llvm.org/docs/LinkTimeOptimization.html +[thinlto]: https://clang.llvm.org/docs/ThinLTO.html +[TLS]: https://llvm.org/docs/LangRef.html#thread-local-storage-models diff --git a/src/doc/rustc-guide/src/appendix/humorust.md b/src/doc/rustc-dev-guide/src/appendix/humorust.md similarity index 80% rename from src/doc/rustc-guide/src/appendix/humorust.md rename to src/doc/rustc-dev-guide/src/appendix/humorust.md index ef926c1c69..8bd9c48a6c 100644 --- a/src/doc/rustc-guide/src/appendix/humorust.md +++ b/src/doc/rustc-dev-guide/src/appendix/humorust.md @@ -10,3 +10,4 @@ enlightening? - [Rust Koans](https://users.rust-lang.org/t/rust-koans/2408/4) - [`break rust;`](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0ab2bd6a9d722e0f05a95e2a5dcf89cc) - [The Nomicon Intro](https://doc.rust-lang.org/stable/nomicon/) +- [`rustc-ty` renaming punfest](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/rustc-ty.20naming.20bikeshed.20.2F.20punfest.20(was.3A.20design.20meeting.202.2E.2E.2E ) diff --git a/src/doc/rustc-guide/src/appendix/stupid-stats.md b/src/doc/rustc-dev-guide/src/appendix/stupid-stats.md similarity index 98% rename from src/doc/rustc-guide/src/appendix/stupid-stats.md rename to src/doc/rustc-dev-guide/src/appendix/stupid-stats.md index 6ed7d1cbd9..ea9b6e0f06 100644 --- a/src/doc/rustc-guide/src/appendix/stupid-stats.md +++ b/src/doc/rustc-dev-guide/src/appendix/stupid-stats.md @@ -61,7 +61,7 @@ Macros and syntax extensions are expanded, and `cfg` attributes will cause some code to disappear. The resulting AST won't have any macros or macro uses left in. -The code for these first two phases is in [libsyntax](https://github.com/rust-lang/rust/tree/master/src/libsyntax). +The code for these first two phases is in [librustc_ast](https://github.com/rust-lang/rust/tree/master/src/librustc_ast). After this phase, the compiler allocates ids to each node in the AST (technically not every node, but most of them). If we are writing out @@ -356,7 +356,7 @@ struct StupidVisitor { The `StupidVisitor` struct just keeps track of the number of `println!`s it has seen and the count for each number of arguments. It implements -`syntax::visit::Visitor` to walk the AST. Mostly we just use the default +`rustc_ast::visit::Visitor` to walk the AST. Mostly we just use the default methods, these walk the AST taking no action. We override `visit_item` and `visit_mac` to implement custom behaviour when we walk into items (items include functions, modules, traits, structs, and so forth, we're only interested in diff --git a/src/doc/rustc-guide/src/borrow_check.md b/src/doc/rustc-dev-guide/src/borrow_check.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check.md rename to src/doc/rustc-dev-guide/src/borrow_check.md diff --git a/src/doc/rustc-guide/src/borrow_check/moves_and_initialization.md b/src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/moves_and_initialization.md rename to src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization.md diff --git a/src/doc/rustc-guide/src/borrow_check/moves_and_initialization/move_paths.md b/src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization/move_paths.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/moves_and_initialization/move_paths.md rename to src/doc/rustc-dev-guide/src/borrow_check/moves_and_initialization/move_paths.md diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference.md similarity index 98% rename from src/doc/rustc-guide/src/borrow_check/region_inference.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference.md index 84d30bdb47..d0da861db1 100644 --- a/src/doc/rustc-guide/src/borrow_check/region_inference.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference.md @@ -86,7 +86,7 @@ use sparse bitsets). The kinds of region elements are as follows: -- Each **location** in the MIR control-flow graph: a location is just +- Each **[`location`]** in the MIR control-flow graph: a location is just the pair of a basic block and an index. This identifies the point **on entry** to the statement with that index (or the terminator, if the index is equal to `statements.len()`). @@ -219,6 +219,7 @@ Here are some of the fields of the struct: [`constraints`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/region_infer/struct.RegionInferenceContext.html#structfield.constraints [`liveness_constraints`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/region_infer/struct.RegionInferenceContext.html#structfield.liveness_constraints +[`location`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/mir/struct.Location.html [`universal_regions`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/region_infer/struct.RegionInferenceContext.html#structfield.universal_regions [`universal_region_relations`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/region_infer/struct.RegionInferenceContext.html#structfield.universal_region_relations [`type_tests`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/region_infer/struct.RegionInferenceContext.html#structfield.type_tests diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference/closure_constraints.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/closure_constraints.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/region_inference/closure_constraints.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference/closure_constraints.md diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference/constraint_propagation.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md similarity index 97% rename from src/doc/rustc-guide/src/borrow_check/region_inference/constraint_propagation.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md index ee86ae1483..6d190ae1ae 100644 --- a/src/doc/rustc-guide/src/borrow_check/region_inference/constraint_propagation.md +++ b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/constraint_propagation.md @@ -100,7 +100,7 @@ much faster, as described shortly. In the code, the set of outlives constraints is given to the region inference context on creation in a parameter of type -[`ConstraintSet`]. The constraint set is basically just a list of `'a: +[`OutlivesConstraintSet`]. The constraint set is basically just a list of `'a: 'b` constraints. ### The outlives constraint graph and SCCs @@ -112,7 +112,7 @@ induces an edge `'a -> 'b`. This conversion happens in the [`RegionInferenceContext::new`] function that creates the inference context. -[`ConstraintSet`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/constraints/struct.OutlivesConstraintSet.html +[`OutlivesConstraintSet`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/constraints/struct.OutlivesConstraintSet.html [graph-fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/constraints/struct.OutlivesConstraintSet.html#method.graph [`RegionInferenceContext::new`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/borrow_check/region_infer/struct.RegionInferenceContext.html#method.new diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference/error_reporting.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/error_reporting.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/region_inference/error_reporting.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference/error_reporting.md diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference/lifetime_parameters.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/lifetime_parameters.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/region_inference/lifetime_parameters.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference/lifetime_parameters.md diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference/member_constraints.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/member_constraints.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/region_inference/member_constraints.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference/member_constraints.md diff --git a/src/doc/rustc-guide/src/borrow_check/region_inference/placeholders_and_universes.md b/src/doc/rustc-dev-guide/src/borrow_check/region_inference/placeholders_and_universes.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/region_inference/placeholders_and_universes.md rename to src/doc/rustc-dev-guide/src/borrow_check/region_inference/placeholders_and_universes.md diff --git a/src/doc/rustc-guide/src/borrow_check/two_phase_borrows.md b/src/doc/rustc-dev-guide/src/borrow_check/two_phase_borrows.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/two_phase_borrows.md rename to src/doc/rustc-dev-guide/src/borrow_check/two_phase_borrows.md diff --git a/src/doc/rustc-guide/src/borrow_check/type_check.md b/src/doc/rustc-dev-guide/src/borrow_check/type_check.md similarity index 100% rename from src/doc/rustc-guide/src/borrow_check/type_check.md rename to src/doc/rustc-dev-guide/src/borrow_check/type_check.md diff --git a/src/doc/rustc-guide/src/bug-fix-procedure.md b/src/doc/rustc-dev-guide/src/bug-fix-procedure.md similarity index 99% rename from src/doc/rustc-guide/src/bug-fix-procedure.md rename to src/doc/rustc-dev-guide/src/bug-fix-procedure.md index 0f6d6c973b..90d8fb48b6 100644 --- a/src/doc/rustc-guide/src/bug-fix-procedure.md +++ b/src/doc/rustc-dev-guide/src/bug-fix-procedure.md @@ -65,7 +65,7 @@ described in more detail below): 1. Once the change has been in the wild for at least one cycle, we can **stabilize the change**, converting those warnings into errors. -Finally, for changes to libsyntax that will affect plugins, the general policy +Finally, for changes to `librustc_ast` that will affect plugins, the general policy is to batch these changes. That is discussed below in more detail. ### Tracking issue diff --git a/src/doc/rustc-guide/src/building/bootstrapping.md b/src/doc/rustc-dev-guide/src/building/bootstrapping.md similarity index 100% rename from src/doc/rustc-guide/src/building/bootstrapping.md rename to src/doc/rustc-dev-guide/src/building/bootstrapping.md diff --git a/src/doc/rustc-guide/src/building/build-install-distribution-artifacts.md b/src/doc/rustc-dev-guide/src/building/build-install-distribution-artifacts.md similarity index 100% rename from src/doc/rustc-guide/src/building/build-install-distribution-artifacts.md rename to src/doc/rustc-dev-guide/src/building/build-install-distribution-artifacts.md diff --git a/src/doc/rustc-guide/src/building/compiler-documenting.md b/src/doc/rustc-dev-guide/src/building/compiler-documenting.md similarity index 100% rename from src/doc/rustc-guide/src/building/compiler-documenting.md rename to src/doc/rustc-dev-guide/src/building/compiler-documenting.md diff --git a/src/doc/rustc-guide/src/building/ctags.md b/src/doc/rustc-dev-guide/src/building/ctags.md similarity index 100% rename from src/doc/rustc-guide/src/building/ctags.md rename to src/doc/rustc-dev-guide/src/building/ctags.md diff --git a/src/doc/rustc-guide/src/building/how-to-build-and-run.md b/src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md similarity index 100% rename from src/doc/rustc-guide/src/building/how-to-build-and-run.md rename to src/doc/rustc-dev-guide/src/building/how-to-build-and-run.md diff --git a/src/doc/rustc-guide/src/building/suggested.md b/src/doc/rustc-dev-guide/src/building/suggested.md similarity index 100% rename from src/doc/rustc-guide/src/building/suggested.md rename to src/doc/rustc-dev-guide/src/building/suggested.md diff --git a/src/doc/rustc-guide/src/closure.md b/src/doc/rustc-dev-guide/src/closure.md similarity index 100% rename from src/doc/rustc-guide/src/closure.md rename to src/doc/rustc-dev-guide/src/closure.md diff --git a/src/doc/rustc-guide/src/codegen.md b/src/doc/rustc-dev-guide/src/codegen.md similarity index 100% rename from src/doc/rustc-guide/src/codegen.md rename to src/doc/rustc-dev-guide/src/codegen.md diff --git a/src/doc/rustc-guide/src/codegen/backend-agnostic.md b/src/doc/rustc-dev-guide/src/codegen/backend-agnostic.md similarity index 98% rename from src/doc/rustc-guide/src/codegen/backend-agnostic.md rename to src/doc/rustc-dev-guide/src/codegen/backend-agnostic.md index 3bf1bde83c..0c501a2cc3 100644 --- a/src/doc/rustc-guide/src/codegen/backend-agnostic.md +++ b/src/doc/rustc-dev-guide/src/codegen/backend-agnostic.md @@ -89,7 +89,7 @@ parameters, that correspond to the following: Although there are already many lifetime parameters in the code, making it generic uncovered situations where the borrow-checker was passing only due to the special nature of the LLVM objects manipulated (they are extern pointers). -For instance, a additional lifetime parameter had to be added to +For instance, an additional lifetime parameter had to be added to `LocalAnalyser` in `analyse.rs`, leading to the definition: ```rust,ignore @@ -179,7 +179,7 @@ addding another backend, the traits definition might be changed in order to offer more flexibility. However, the current separation between backend-agnostic and LLVM-specific code -has allows the reuse of a significant part of the old `rustc_codegen_llvm`. +has allowed the reuse of a significant part of the old `rustc_codegen_llvm`. Here is the new LOC breakdown between backend-agnostic (BA) and LLVM for the most important elements: diff --git a/src/doc/rustc-guide/src/codegen/debugging.md b/src/doc/rustc-dev-guide/src/codegen/debugging.md similarity index 98% rename from src/doc/rustc-guide/src/codegen/debugging.md rename to src/doc/rustc-dev-guide/src/codegen/debugging.md index 4eab306068..0da29bfb9e 100644 --- a/src/doc/rustc-guide/src/codegen/debugging.md +++ b/src/doc/rustc-dev-guide/src/codegen/debugging.md @@ -123,6 +123,8 @@ tutorial above): - The `-Ztime-llvm-passes` option measures the time of each LLVM pass - The `-Zverify-llvm-ir` option will verify the LLVM IR for correctness - The `-Zno-parallel-llvm` will disable parallel compilation of distinct compilation units +- The `-Zllvm-time-trace` option will output a Chrome profiler compatible JSON file + which contains details and timings for LLVM passes. ### Filing LLVM bug reports diff --git a/src/doc/rustc-guide/src/codegen/updating-llvm.md b/src/doc/rustc-dev-guide/src/codegen/updating-llvm.md similarity index 100% rename from src/doc/rustc-guide/src/codegen/updating-llvm.md rename to src/doc/rustc-dev-guide/src/codegen/updating-llvm.md diff --git a/src/doc/rustc-guide/src/compiler-debugging.md b/src/doc/rustc-dev-guide/src/compiler-debugging.md similarity index 100% rename from src/doc/rustc-guide/src/compiler-debugging.md rename to src/doc/rustc-dev-guide/src/compiler-debugging.md diff --git a/src/doc/rustc-guide/src/compiler-team.md b/src/doc/rustc-dev-guide/src/compiler-team.md similarity index 100% rename from src/doc/rustc-guide/src/compiler-team.md rename to src/doc/rustc-dev-guide/src/compiler-team.md diff --git a/src/doc/rustc-guide/src/compiletest.md b/src/doc/rustc-dev-guide/src/compiletest.md similarity index 100% rename from src/doc/rustc-guide/src/compiletest.md rename to src/doc/rustc-dev-guide/src/compiletest.md diff --git a/src/doc/rustc-guide/src/const-eval.md b/src/doc/rustc-dev-guide/src/const-eval.md similarity index 100% rename from src/doc/rustc-guide/src/const-eval.md rename to src/doc/rustc-dev-guide/src/const-eval.md diff --git a/src/doc/rustc-guide/src/conventions.md b/src/doc/rustc-dev-guide/src/conventions.md similarity index 99% rename from src/doc/rustc-guide/src/conventions.md rename to src/doc/rustc-dev-guide/src/conventions.md index 7f7bf32e21..303eedd4ee 100644 --- a/src/doc/rustc-guide/src/conventions.md +++ b/src/doc/rustc-dev-guide/src/conventions.md @@ -12,7 +12,7 @@ at the moment, however, it follows a rather more *chaotic* style. We do have some mandatory formatting conventions, which are automatically enforced by a script we affectionately call the "tidy" script. The tidy script runs automatically when you do `./x.py test` and can be run -in isolation with `./x.py test src/tools/tidy`. +in isolation with `./x.py test tidy`. [fmt]: https://github.com/rust-lang-nursery/fmt-rfcs diff --git a/src/doc/rustc-guide/src/crates-io.md b/src/doc/rustc-dev-guide/src/crates-io.md similarity index 100% rename from src/doc/rustc-guide/src/crates-io.md rename to src/doc/rustc-dev-guide/src/crates-io.md diff --git a/src/doc/rustc-guide/src/debugging-support-in-rustc.md b/src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md similarity index 98% rename from src/doc/rustc-guide/src/debugging-support-in-rustc.md rename to src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md index 3d08cc8253..a11edba785 100644 --- a/src/doc/rustc-guide/src/debugging-support-in-rustc.md +++ b/src/doc/rustc-dev-guide/src/debugging-support-in-rustc.md @@ -77,13 +77,13 @@ the trait object. **TODO**: Figure out if the following should be mentioned in the GDB-Rust document rather than this guide page so there is no duplication. This is regarding the following comments: -[This comment by Tom](https://github.com/rust-lang/rustc-guide/pull/316#discussion_r284027340) +[This comment by Tom](https://github.com/rust-lang/rustc-dev-guide/pull/316#discussion_r284027340) > gdb's Rust extensions and limitations are documented in the gdb manual: https://sourceware.org/gdb/onlinedocs/gdb/Rust.html -- however, this neglects to mention that gdb convenience variables and registers follow the gdb $ convention, and that the Rust parser implements the gdb @ extension. -[This question by Aman](https://github.com/rust-lang/rustc-guide/pull/316#discussion_r285401353) +[This question by Aman](https://github.com/rust-lang/rustc-dev-guide/pull/316#discussion_r285401353) > @tromey do you think we should mention this part in the GDB-Rust document rather than this document so there is no duplication etc.? @@ -276,7 +276,7 @@ set the breakpoints and what happens when you step it. * New demangler in LLVM or LLDB. **TODO**: Check the location of the demangler source. -[Question on Github](https://github.com/rust-lang/rustc-guide/pull/316#discussion_r283062536). +[Question on Github](https://github.com/rust-lang/rustc-dev-guide/pull/316#discussion_r283062536). #### Reuse Rust compiler for expressions diff --git a/src/doc/rustc-guide/src/diagnostics.md b/src/doc/rustc-dev-guide/src/diagnostics.md similarity index 97% rename from src/doc/rustc-guide/src/diagnostics.md rename to src/doc/rustc-dev-guide/src/diagnostics.md index 0bf869ccdd..c112f3471d 100644 --- a/src/doc/rustc-guide/src/diagnostics.md +++ b/src/doc/rustc-dev-guide/src/diagnostics.md @@ -31,7 +31,7 @@ usually have names like `span_err` or `struct_span_err` or `span_warn`, etc... There are lots of them; they emit different types of "errors", such as warnings, errors, fatal errors, suggestions, etc. -[parsesses]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/sess/struct.ParseSess.html +[parsesses]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/parse/struct.ParseSess.html [session]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/struct.Session.html In general, there are two classes of such methods: ones that emit an error @@ -315,19 +315,19 @@ processed. [`Session`][sessbl] and [`ParseSess`][parsebl] both have system automatically takes care of handling buffered lints later. [sessbl]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/struct.Session.html#method.buffer_lint -[parsebl]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/sess/struct.ParseSess.html#method.buffer_lint +[parsebl]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/parse/struct.ParseSess.html#method.buffer_lint Thus, to define a lint that runs early in the compilation, one defines a lint like normal but invokes the lint with `buffer_lint`. #### Linting even earlier in the compiler -The parser (`libsyntax`) is interesting in that it cannot have dependencies on +The parser (`librustc_ast`) is interesting in that it cannot have dependencies on any of the other `librustc*` crates. In particular, it cannot depend on `librustc::lint` or `librustc_lint`, where all of the compiler linting infrastructure is defined. That's troublesome! -To solve this, `libsyntax` defines its own buffered lint type, which +To solve this, `librustc_ast` defines its own buffered lint type, which `ParseSess::buffer_lint` uses. After macro expansion, these buffered lints are then dumped into the `Session::buffered_lints` used by the rest of the compiler. @@ -358,7 +358,7 @@ the structured JSON and see the "human" output (well, _sans_ colors) without having to compile everything twice. The "human" readable and the json format emitter can be found under -librustc_errors, both were moved from the libsyntax crate to the +librustc_errors, both were moved from the `librustc_ast` crate to the [librustc_errors crate](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/index.html). The JSON emitter defines [its own `Diagnostic` diff --git a/src/doc/rustc-guide/src/diagnostics/diagnostic-codes.md b/src/doc/rustc-dev-guide/src/diagnostics/diagnostic-codes.md similarity index 98% rename from src/doc/rustc-guide/src/diagnostics/diagnostic-codes.md rename to src/doc/rustc-dev-guide/src/diagnostics/diagnostic-codes.md index 22d9b12c37..0e923c5e1b 100644 --- a/src/doc/rustc-guide/src/diagnostics/diagnostic-codes.md +++ b/src/doc/rustc-dev-guide/src/diagnostics/diagnostic-codes.md @@ -12,7 +12,7 @@ code. This is a bit tricky since the codes are defined in various crates. To do it, run this obscure command: ``` -./x.py test --stage 0 src/tools/tidy +./x.py test --stage 0 tidy ``` This will invoke the tidy script, which generally checks that your code obeys diff --git a/src/doc/rustc-guide/src/diagnostics/lintstore.md b/src/doc/rustc-dev-guide/src/diagnostics/lintstore.md similarity index 100% rename from src/doc/rustc-guide/src/diagnostics/lintstore.md rename to src/doc/rustc-dev-guide/src/diagnostics/lintstore.md diff --git a/src/doc/rustc-guide/src/generic_arguments.md b/src/doc/rustc-dev-guide/src/generic_arguments.md similarity index 100% rename from src/doc/rustc-guide/src/generic_arguments.md rename to src/doc/rustc-dev-guide/src/generic_arguments.md diff --git a/src/doc/rustc-dev-guide/src/generics.md b/src/doc/rustc-dev-guide/src/generics.md new file mode 100644 index 0000000000..310b9cda69 --- /dev/null +++ b/src/doc/rustc-dev-guide/src/generics.md @@ -0,0 +1,144 @@ +# Generics and substitutions + +Given a generic type `MyType`, we may want to swap out the generics `A, B, …` for some +other types (possibly other generics or concrete types). We do this a lot while doing type +inference, type checking, and trait solving. Conceptually, during these routines, we may find out +that one type is equal to another type and want to swap one out for the other and then swap that out +for another type and so on until we eventually get some concrete types (or an error). + +In rustc this is done using the `SubstsRef` that we mentioned above (“substs” = “substitutions”). +Conceptually, you can think of `SubstsRef` of a list of types that are to be substituted for the +generic type parameters of the ADT. + +`SubstsRef` is a type alias of `List>` (see [`List` rustdocs][list]). +[`GenericArg`] is essentially a space-efficient wrapper around [`GenericArgKind`], which is an enum +indicating what kind of generic the type parameter is (type, lifetime, or const). Thus, `SubstsRef` +is conceptually like a `&'tcx [GenericArgKind<'tcx>]` slice (but it is actually a `List`). + +[list]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.List.html +[`GenericArg`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/struct.GenericArg.html +[`GenericArgKind`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/enum.GenericArgKind.html + +So why do we use this `List` type instead of making it really a slice? It has the length "inline", +so `&List` is only 32 bits. As a consequence, it cannot be "subsliced" (that only works if the +length is out of line). + +This also implies that you can check two `List`s for equality via `==` (which would be not be +possible for ordinary slices). This is precisely because they never represent a "sub-list", only the +complete `List`, which has been hashed and interned. + +So pulling it all together, let’s go back to our example above: + +```rust,ignore +struct MyStruct +``` + +- There would be an `AdtDef` (and corresponding `DefId`) for `MyStruct`. +- There would be a `TyKind::Param` (and corresponding `DefId`) for `T` (more later). +- There would be a `SubstsRef` containing the list `[GenericArgKind::Type(Ty(T))]` + - The `Ty(T)` here is my shorthand for entire other `ty::Ty` that has `TyKind::Param`, which we + mentioned in the previous point. +- This is one `TyKind::Adt` containing the `AdtDef` of `MyStruct` with the `SubstsRef` above. + +Finally, we will quickly mention the +[`Generics`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.Generics.html) type. It +is used to give information about the type parameters of a type. + +### Unsubstituted Generics + +So above, recall that in our example the `MyStruct` struct had a generic type `T`. When we are (for +example) type checking functions that use `MyStruct`, we will need to be able to refer to this type +`T` without actually knowing what it is. In general, this is true inside all generic definitions: we +need to be able to work with unknown types. This is done via `TyKind::Param` (which we mentioned in +the example above). + +Each `TyKind::Param` contains two things: the name and the index. In general, the index fully +defines the parameter and is used by most of the code. The name is included for debug print-outs. +There are two reasons for this. First, the index is convenient, it allows you to include into the +list of generic arguments when substituting. Second, the index is more robust. For example, you +could in principle have two distinct type parameters that use the same name, e.g. `impl Foo { +fn bar() { .. } }`, although the rules against shadowing make this difficult (but those language +rules could change in the future). + +The index of the type parameter is an integer indicating its order in the list of the type +parameters. Moreover, we consider the list to include all of the type parameters from outer scopes. +Consider the following example: + +```rust,ignore +struct Foo { + // A would have index 0 + // B would have index 1 + + .. // some fields +} +impl Foo { + fn method() { + // inside here, X, Y and Z are all in scope + // X has index 0 + // Y has index 1 + // Z has index 2 + } +} +``` + +When we are working inside the generic definition, we will use `TyKind::Param` just like any other +`TyKind`; it is just a type after all. However, if we want to use the generic type somewhere, then +we will need to do substitutions. + +For example suppose that the `Foo` type from the previous example has a field that is a +`Vec`. Observe that `Vec` is also a generic type. We want to tell the compiler that the type +parameter of `Vec` should be replaced with the `A` type parameter of `Foo`. We do that with +substitutions: + +```rust,ignore +struct Foo { // Adt(Foo, &[Param(0), Param(1)]) + x: Vec, // Adt(Vec, &[Param(0)]) + .. +} + +fn bar(foo: Foo) { // Adt(Foo, &[u32, f32]) + let y = foo.x; // Vec => Vec +} +``` + +This example has a few different substitutions: + +- In the definition of `Foo`, in the type of the field `x`, we replace `Vec`'s type parameter with + `Param(0)`, the first parameter of `Foo`, so that the type of `x` is `Vec`. +- In the function `bar`, we specify that we want a `Foo`. This means that we will + substitute `Param(0)` and `Param(1)` with `u32` and `f32`. +- In the body of `bar`, we access `foo.x`, which has type `Vec`, but `Param(0)` has been + substituted for `u32`, so `foo.x` has type `Vec`. + +Let’s look a bit more closely at that last substitution to see why we use indexes. If we want to +find the type of `foo.x`, we can get generic type of `x`, which is `Vec`. Now we can take +the index `0` and use it to find the right type substitution: looking at `Foo`'s `SubstsRef`, we +have the list `[u32, f32]` , since we want to replace index `0`, we take the 0-th index of this +list, which is `u32`. Voila! + +You may have a couple of followup questions… + + **`type_of`** How do we get the “generic type of `x`"? You can get the type of pretty much anything + with the `tcx.type_of(def_id)` query. In this case, we would pass the `DefId` of the field `x`. + The `type_of` query always returns the definition with the generics that are in scope of the + definition. For example, `tcx.type_of(def_id_of_my_struct)` would return the “self-view” of + `MyStruct`: `Adt(Foo, &[Param(0), Param(1)])`. + +**`subst`** How do we actually do the substitutions? There is a function for that too! You use +[`subst`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/trait.Subst.html) to +replace a `SubstRef` with another list of types. + +[Here is an example of actually using `subst` in the compiler][substex]. The exact details are not +too important, but in this piece of code, we happen to be converting from the `rustc_hir::Ty` to +a real `ty::Ty`. You can see that we first get some substitutions (`substs`). Then we call +`type_of` to get a type and call `ty.subst(substs)` to get a new version of `ty` with +the substitutions made. + +[substex]: https://github.com/rust-lang/rust/blob/597f432489f12a3f33419daa039ccef11a12c4fd/src/librustc_typeck/astconv.rs#L942-L953 + +**Note on indices:** It is possible for the indices in `Param` to not match with what we expect. For +example, the index could be out of bounds or it could be the index of a lifetime when we were +expecting a type. These sorts of errors would be caught earlier in the compiler when translating +from a `rustc_hir::Ty` to a `ty::Ty`. If they occur later, that is a compiler bug. + + diff --git a/src/doc/rustc-guide/src/high-level-overview.md b/src/doc/rustc-dev-guide/src/high-level-overview.md similarity index 97% rename from src/doc/rustc-guide/src/high-level-overview.md rename to src/doc/rustc-dev-guide/src/high-level-overview.md index e4b9ff3720..76f4bc9553 100644 --- a/src/doc/rustc-guide/src/high-level-overview.md +++ b/src/doc/rustc-dev-guide/src/high-level-overview.md @@ -7,7 +7,7 @@ there live many crates. These crates contain the sources for the standard library and the compiler. This document, of course, focuses on the latter. -Rustc consists of a number of crates, including `syntax`, +Rustc consists of a number of crates, including `rustc_ast`, `rustc`, `rustc_target`, `rustc_codegen`, `rustc_driver`, and many more. The source for each crate can be found in a directory like `src/libXXX`, where `XXX` is the crate name. @@ -33,7 +33,7 @@ rustc_codegen rustc_borrowck ... rustc_metadata rustc | v - syntax + rustc_ast / \ / \ rustc_span rustc_builtin_macros @@ -92,7 +92,7 @@ take: 1. **Parsing input** - this processes the `.rs` files and produces the AST ("abstract syntax tree") - - the AST is defined in `src/libsyntax/ast.rs`. It is intended to match the lexical + - the AST is defined in `src/librustc_ast/ast.rs`. It is intended to match the lexical syntax of the Rust language quite closely. 2. **Name resolution, macro expansion, and configuration** - once parsing is complete, we process the AST recursively, resolving diff --git a/src/doc/rustc-guide/src/hir-debugging.md b/src/doc/rustc-dev-guide/src/hir-debugging.md similarity index 100% rename from src/doc/rustc-guide/src/hir-debugging.md rename to src/doc/rustc-dev-guide/src/hir-debugging.md diff --git a/src/doc/rustc-guide/src/hir.md b/src/doc/rustc-dev-guide/src/hir.md similarity index 98% rename from src/doc/rustc-guide/src/hir.md rename to src/doc/rustc-dev-guide/src/hir.md index 60a3c3b8bb..2c3e44a72b 100644 --- a/src/doc/rustc-guide/src/hir.md +++ b/src/doc/rustc-dev-guide/src/hir.md @@ -100,7 +100,7 @@ sorts of identifiers in active use: [`DefId`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/def_id/struct.DefId.html [`HirId`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir_id/struct.HirId.html [`BodyId`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/struct.BodyId.html -[`NodeId`]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/struct.NodeId.html +[`NodeId`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/node_id/struct.NodeId.html We also have an internal map to go from `DefId` to what’s called "Def path". "Def path" is like a module path but a bit more rich. For example, it may be `crate::foo::MyStruct` that identifies diff --git a/src/doc/rustc-guide/src/ice-breaker/about.md b/src/doc/rustc-dev-guide/src/ice-breaker/about.md similarity index 94% rename from src/doc/rustc-guide/src/ice-breaker/about.md rename to src/doc/rustc-dev-guide/src/ice-breaker/about.md index 7869bdbce9..e71001e5bd 100644 --- a/src/doc/rustc-guide/src/ice-breaker/about.md +++ b/src/doc/rustc-dev-guide/src/ice-breaker/about.md @@ -49,6 +49,7 @@ cargo run add-person $your_user_name Example PRs: * [Example of adding yourself to the LLVM ICE-breakers.](https://github.com/rust-lang/team/pull/140) +* [Example of adding yourself to the Cleanup Crew ICE-breakers.](https://github.com/rust-lang/team/pull/221) ## Tagging an issue for an ICE-breaker group @@ -58,6 +59,7 @@ team. For example: ```text @rustbot ping icebreakers-llvm +@rustbot ping icebreakers-cleanup-crew ``` **Note though that this should only be done by compiler team members diff --git a/src/doc/rustc-dev-guide/src/ice-breaker/cleanup-crew.md b/src/doc/rustc-dev-guide/src/ice-breaker/cleanup-crew.md new file mode 100644 index 0000000000..436b51fd18 --- /dev/null +++ b/src/doc/rustc-dev-guide/src/ice-breaker/cleanup-crew.md @@ -0,0 +1,114 @@ +# Cleanup Crew + +**Github Label:** [ICEBreaker-Cleanup-Crew] + +[ICEBreaker-Cleanup-Crew]: https://github.com/rust-lang/rust/labels/ICEBreaker-Cleanup-Crew + +The "Cleanup Crew" are focused on improving bug reports. Specifically, +the goal is to try to ensure that every bug report has all the +information that will be needed for someone to fix it: + +* a minimal, standalone example that shows the problem +* links to duplicates or related bugs +* if the bug is a regression (something that used to work, but no longer does), + then a bisection to the PR or nightly that caused the regression + +This kind of cleanup is invaluable in getting bugs fixed. Better +still, it can be done by anybody who knows Rust, without any +particularly deep knowledge of the compiler. + +Let's look a bit at the workflow for doing "cleanup crew" actions. + +## Finding a minimal, standalone example + +Here the ultimate goal is to produce an example that reproduces the same +problem but without relying on any external crates. Such a test ought to contain +as little code as possible, as well. This will make it much easier to isolate the problem. + +However, even if the "ultimate minimal test" cannot be achieved, it's +still useful to post incremental minimizations. For example, if you +can eliminate some of the external dependencies, that is helpful, and +so forth. + +It's particularly useful to reduce to an example that works +in the [Rust playground](https://play.rust-lang.org/), rather than +requiring people to checkout a cargo build. + +There are many resources for how to produce minimized test cases. Here +are a few: + +* The [rust-reduce](https://github.com/jethrogb/rust-reduce) tool can try to reduce + code automatically. + * The [C-reduce](https://embed.cs.utah.edu/creduce/) tool also works + on Rust code, though it requires that you start from a single + file. (XXX link to some post explaining how to do it?) +* pnkfelix's [Rust Bug Minimization Patterns] blog post + * This post focuses on "heavy bore" techniques, where you are + starting with a large, complex cargo project that you wish to + narrow down to something standalone. + +[Rust Bug Minimization Patterns]: http://blog.pnkfx.org/blog/2019/11/18/rust-bug-minimization-patterns/ + +## Links to duplicate or related bugs + +If you are on the "Cleanup Crew", you will sometimes see multiple bug +reports that seem very similar. You can link one to the other just by +mentioning the other bug number in a Github comment. Sometimes it is +useful to close duplicate bugs. But if you do so, you should always +copy any test case from the bug you are closing to the other bug that +remains open, as sometimes duplicate-looking bugs will expose +different facets of the same problem. + +## Bisecting regressions + +For regressions (something that used to work, but no longer does), it +is super useful if we can figure out precisely when the code stopped +working. The gold standard is to be able to identify the precise +**PR** that broke the code, so we can ping the author, but even +narrowing it down to a nightly build is helpful, especially as that +then gives us a range of PRs. (One other challenge is that we +sometimes land "rollup" PRs, which combine multiple PRs into one.) + +### cargo-bisect-rustc + +To help in figuring out the cause of a regression we have a tool +called [cargo-bisect-rustc]. It will automatically download and test +various builds of rustc. For recent regressions, it is even able to +use the builds from our CI to track down the regression to a specific +PR; for older regressions, it will simply identify a nightly. + +To learn to use [cargo-bisect-rustc], check out [this blog +post][learn], which gives a quick introduction to how it works. You +can also ask questions at the Zulip stream +[`#t-compiler/cargo-bisect-rustc`][zcbr], or help in improving the tool. + +[cargo-bisect-rustc]: https://github.com/rust-lang/cargo-bisect-rustc/ +[learn]: https://blog.rust-lang.org/inside-rust/2019/12/18/bisecting-rust-compiler.html +[zcbr]: https://rust-lang.zulipchat.com/#narrow/stream/217417-t-compiler.2Fcargo-bisect-rustc + +### identifying the range of PRs in a nightly + +If the regression occurred more than 90 days ago, then +cargo-bisect-rustc will not able to identify the particular PR that +caused the regression, just the nightly build. In that case, we can +identify the set of PRs that this corresponds to by using the git +history. + +The command `rustc +nightly -vV` will cause rustc to output a number +of useful bits of version info, including the `commit-hash`. Given the +commit-hash of two nightly versions, you can find all of PRs that have +landed in between by taking the following steps: + +1. Go to an update checkout of the [rust-lang/rust] repository +2. Execute the command `git log --author=bors --format=oneline SHA1..SHA2` + * This will list out all of the commits by bors, which is our merge bot + * Each commit corresponds to one PR, and information about the PR should be in the description +3. Copy and paste that information into the bug report + +Often, just eye-balling the PR descriptions (which are included in the +commit messages) will give you a good idea which one likely caused the +problem. But if you're unsure feel free to just ping the compiler team +(`@rust-lang/compiler`) or else to ping the authors of the PR +themselves. + +[rust-lang/rust]: https://github.com/rust-lang/rust/ diff --git a/src/doc/rustc-guide/src/ice-breaker/llvm.md b/src/doc/rustc-dev-guide/src/ice-breaker/llvm.md similarity index 93% rename from src/doc/rustc-guide/src/ice-breaker/llvm.md rename to src/doc/rustc-dev-guide/src/ice-breaker/llvm.md index e0c90fdafc..8a8ef411b4 100644 --- a/src/doc/rustc-guide/src/ice-breaker/llvm.md +++ b/src/doc/rustc-dev-guide/src/ice-breaker/llvm.md @@ -16,7 +16,7 @@ the result of an LLVM upgrade. The goal here is: ## Helpful tips and options The ["Debugging LLVM"][d] section of the -rustc-guide gives a step-by-step process for how to help debug bugs +rustc-dev-guide gives a step-by-step process for how to help debug bugs caused by LLVM. In particular, it discusses how to emit LLVM IR, run the LLVM IR optimization pipeliness, and so forth. You may also find it useful to look at the various codegen options listed under `-Chelp` diff --git a/src/doc/rustc-guide/src/img/rustc_stages.svg b/src/doc/rustc-dev-guide/src/img/rustc_stages.svg similarity index 100% rename from src/doc/rustc-guide/src/img/rustc_stages.svg rename to src/doc/rustc-dev-guide/src/img/rustc_stages.svg diff --git a/src/doc/rustc-guide/src/implementing_new_features.md b/src/doc/rustc-dev-guide/src/implementing_new_features.md similarity index 95% rename from src/doc/rustc-guide/src/implementing_new_features.md rename to src/doc/rustc-dev-guide/src/implementing_new_features.md index ff9a709e6f..780950c71c 100644 --- a/src/doc/rustc-guide/src/implementing_new_features.md +++ b/src/doc/rustc-dev-guide/src/implementing_new_features.md @@ -106,8 +106,8 @@ for stabilization in a checklist, e.g., - [ ] Implement the RFC. (CC @rust-lang/compiler -- can anyone write up mentoring instructions?) -- [ ] Adjust the documentation. ([See instructions on rustc-guide.](https://rust-lang.github.io/rustc-guide/stabilization_guide.html#documentation-prs)) -- [ ] Stabilize the feature. ([See instructions on rustc-guide.](https://rust-lang.github.io/rustc-guide/stabilization_guide.html#stabilization-pr)) +- [ ] Adjust the documentation. ([See instructions on rustc-dev-guide.](https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs)) +- [ ] Stabilize the feature. ([See instructions on rustc-dev-guide.](https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr)) ``` @@ -129,7 +129,7 @@ a new unstable feature: in the active `declare_features` block: ```rust,ignore - // description of feature + /// description of feature (active, $feature_name, "$current_nightly_version", Some($tracking_issue_number), $edition) ``` @@ -175,7 +175,7 @@ a new unstable feature: 8. Get your PR reviewed and land it. You have now successfully implemented a feature in Rust! -[`GatedSpans`]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/sess/struct.GatedSpans.html +[`GatedSpans`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/parse/struct.GatedSpans.html [`rustc_ast_passes::feature_gate::check_crate`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast_passes/feature_gate/fn.check_crate.html [value the stability of Rust]: https://github.com/rust-lang/rfcs/blob/master/text/1122-language-semver.md [stability in code]: #stability-in-code diff --git a/src/doc/rustc-guide/src/incrcomp-debugging.md b/src/doc/rustc-dev-guide/src/incrcomp-debugging.md similarity index 100% rename from src/doc/rustc-guide/src/incrcomp-debugging.md rename to src/doc/rustc-dev-guide/src/incrcomp-debugging.md diff --git a/src/doc/rustc-guide/src/lowering.md b/src/doc/rustc-dev-guide/src/lowering.md similarity index 100% rename from src/doc/rustc-guide/src/lowering.md rename to src/doc/rustc-dev-guide/src/lowering.md diff --git a/src/doc/rustc-guide/src/macro-expansion.md b/src/doc/rustc-dev-guide/src/macro-expansion.md similarity index 96% rename from src/doc/rustc-guide/src/macro-expansion.md rename to src/doc/rustc-dev-guide/src/macro-expansion.md index 9280fa9bc4..db58733ad1 100644 --- a/src/doc/rustc-guide/src/macro-expansion.md +++ b/src/doc/rustc-dev-guide/src/macro-expansion.md @@ -1,6 +1,6 @@ # Macro expansion -> `libsyntax`, `librustc_expand`, and `librustc_builtin_macros` are all undergoing +> `librustc_ast`, `librustc_expand`, and `librustc_builtin_macros` are all undergoing > refactoring, so some of the links in this chapter may be broken. Macro expansion happens during parsing. `rustc` has two parsers, in fact: the @@ -69,14 +69,13 @@ defined in [`src/librustc_expand/mbe/macro_parser.rs`][code_mp]. The interface of the macro parser is as follows (this is slightly simplified): ```rust,ignore -fn parse( - sess: ParserSession, - tts: TokenStream, - ms: &[TokenTree] +fn parse_tt( + parser: &mut Cow, + ms: &[TokenTree], ) -> NamedParseResult ``` -In this interface: +We use these items in macro parser: - `sess` is a "parsing session", which keeps track of some metadata. Most notably, this is used to keep track of errors that are generated so they can @@ -211,7 +210,7 @@ TODO: maybe something about macros 2.0? [code_dir]: https://github.com/rust-lang/rust/tree/master/src/librustc_expand/mbe [code_mp]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_expand/mbe/macro_parser [code_mr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_expand/mbe/macro_rules -[code_parse_int]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_expand/mbe/macro_parser/fn.parse.html +[code_parse_int]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_expand/mbe/macro_parser/fn.parse_tt.html [parsing]: ./the-parser.html @@ -228,7 +227,7 @@ just have a zulip discussion where you tell us (WG-learning) everything you know about macros/expansion/hygiene. We were thinking this could be less formal (and less work for you) than compiler lecture series lecture... thoughts? -mark-i-m: The goal is to fill out that long-standing gap in the rustc-guide +mark-i-m: The goal is to fill out that long-standing gap in the rustc-dev-guide Vadim Petrochenkov: Ok, I'm at UTC+03:00 and generally available in the evenings (or weekends). @@ -362,24 +361,24 @@ be accessed from any Ident without any context) librustc_span/lib.rs - some secondary methods like macro backtrace using primary methods from hygiene.rs librustc_builtin_macros - implementations of built-in macros (including macro attributes and derives) and some other early code generation facilities like injection of -standard library imports or generation of test harness. libsyntax/config.rs - +standard library imports or generation of test harness. librustc_ast/config.rs - implementation of cfg/cfg_attr (they treated specially from other macros), -should probably be moved into libsyntax/ext. libsyntax/tokenstream.rs + -libsyntax/parse/token.rs - structures for compiler-side tokens, token trees, -and token streams. libsyntax/ext - various expansion-related stuff -libsyntax/ext/base.rs - basic structures used by expansion -libsyntax/ext/expand.rs - some expansion structures and the bulk of expansion +should probably be moved into librustc_ast/ext. librustc_ast/tokenstream.rs + +librustc_ast/parse/token.rs - structures for compiler-side tokens, token trees, +and token streams. librustc_ast/ext - various expansion-related stuff +librustc_ast/ext/base.rs - basic structures used by expansion +librustc_ast/ext/expand.rs - some expansion structures and the bulk of expansion infrastructure code - collecting macro invocations, calling into resolve for them, calling their expanding functions, and integrating the results back into -AST libsyntax/ext/placeholder.rs - the part of expand.rs responsible for +AST librustc_ast/ext/placeholder.rs - the part of expand.rs responsible for "integrating the results back into AST" basicallly, "placeholder" is a temporary AST node replaced with macro expansion result nodes -libsyntax/ext/builer.rs - helper functions for building AST for built-in macros +librustc_ast/ext/builer.rs - helper functions for building AST for built-in macros in librustc_builtin_macros (and user-defined syntactic plugins previously), can probably -be moved into librustc_builtin_macros these days libsyntax/ext/proc_macro.rs + -libsyntax/ext/proc_macro_server.rs - interfaces between the compiler and the +be moved into librustc_builtin_macros these days librustc_ast/ext/proc_macro.rs + +librustc_ast/ext/proc_macro_server.rs - interfaces between the compiler and the stable proc_macro library, converting tokens and token streams between the two -representations and sending them through C ABI libsyntax/ext/tt - +representations and sending them through C ABI librustc_ast/ext/tt - implementation of macro_rules, turns macro_rules DSL into something with signature Fn(TokenStream) -> TokenStream that can eat and produce tokens, @mark-i-m knows more about this librustc_resolve/macros.rs - resolving macro @@ -409,8 +408,8 @@ piece of AST, etc), this is an enum that lists them ProcMacro/TTMacroExpander/AttrProcMacro/MultiItemModifier - traits representing the expander signatures (TODO: change and rename the signatures into something more consistent) trait Resolver - a trait used to break crate dependencies (so -resolver services can be used in libsyntax, despite librustc_resolve and pretty -much everything else depending on libsyntax) ExtCtxt/ExpansionData - various +resolver services can be used in librustc_ast, despite librustc_resolve and pretty +much everything else depending on librustc_ast) ExtCtxt/ExpansionData - various intermediate data kept and used by expansion infra in the process of its work AstFragment - a piece of AST that can be produced by a macro (may include multiple homogeneous AST nodes, like e.g. a list of items) Annotatable - a @@ -629,7 +628,7 @@ Vadim Petrochenkov: A thread for offline questions-answers would be good too. A thread for offline questions-answers would be good too. I don't mind using this thread, since it already has a lot of info in it. We -also plan to summarize the info from this thread into the rustc-guide. +also plan to summarize the info from this thread into the rustc-dev-guide. Sure, why not. @@ -649,7 +648,7 @@ eager expansion... Santiago Pastorino: sorry but I couldn't follow that much today, will read it when I have some time later -Santiago Pastorino: btw https://github.com/rust-lang/rustc-guide/issues/398 +Santiago Pastorino: btw https://github.com/rust-lang/rustc-dev-guide/issues/398 mark-i-m: @Vadim Petrochenkov Would 7pm UTC on August 21 work for a followup? diff --git a/src/doc/rustc-dev-guide/src/memory.md b/src/doc/rustc-dev-guide/src/memory.md new file mode 100644 index 0000000000..bfec4fe198 --- /dev/null +++ b/src/doc/rustc-dev-guide/src/memory.md @@ -0,0 +1,88 @@ +# Memory Management in Rustc + +Rustc tries to be pretty careful how it manages memory. The compiler allocates +_a lot_ of data structures throughout compilation, and if we are not careful, +it will take a lot of time and space to do so. + +One of the main way the compiler manages this is using arenas and interning. + +## Arenas and Interning + +We create a LOT of data structures during compilation. For performance reasons, +we allocate them from a global memory pool; they are each allocated once from a +long-lived *arena*. This is called _arena allocation_. This system reduces +allocations/deallocations of memory. It also allows for easy comparison of +types for equality: for each interned type `X`, we implemented [`PartialEq for +X`][peqimpl], so we can just compare pointers. The [`CtxtInterners`] type +contains a bunch of maps of interned types and the arena itself. + +[peqimpl]: https://github.com/rust-lang/rust/blob/3ee936378662bd2e74be951d6a7011a95a6bd84d/src/librustc/ty/mod.rs#L528-L534 +[`CtxtInterners`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.CtxtInterners.html#structfield.arena + +### Example: `ty::TyS` + +Taking the example of [`ty::TyS`] which represents a type in the compiler (you +can read more [here](./ty.md)). Each time we want to construct a type, the +compiler doesn’t naively allocate from the buffer. Instead, we check if that +type was already constructed. If it was, we just get the same pointer we had +before, otherwise we make a fresh pointer. With this schema if we want to know +if two types are the same, all we need to do is compare the pointers which is +efficient. `TyS` is carefully setup so you never construct them on the stack. +You always allocate them from this arena and you always intern them so they are +unique. + +At the beginning of the compilation we make a buffer and each time we need to allocate a type we use +some of this memory buffer. If we run out of space we get another one. The lifetime of that buffer +is `'tcx`. Our types are tied to that lifetime, so when compilation finishes all the memory related +to that buffer is freed and our `'tcx` references would be invalid. + +In addition to types, there are a number of other arena-allocated data structures that you can +allocate, and which are found in this module. Here are a few examples: + +- [`Substs`][subst], allocated with `mk_substs` – this will intern a slice of types, often used to + specify the values to be substituted for generics (e.g. `HashMap` would be represented + as a slice `&'tcx [tcx.types.i32, tcx.types.u32]`). +- [`TraitRef`], typically passed by value – a **trait reference** consists of a reference to a trait + along with its various type parameters (including `Self`), like `i32: Display` (here, the def-id + would reference the `Display` trait, and the substs would contain `i32`). Note that `def-id` is + defined and discussed in depth in the `AdtDef and DefId` section. +- [`Predicate`] defines something the trait system has to prove (see `traits` module). + +[subst]: ./generic_arguments.html#subst +[`TraitRef`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TraitRef.html +[`Predicate`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.Predicate.html + +[`ty::TyS`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyS.html + +## The tcx and how it uses lifetimes + +The `tcx` ("typing context") is the central data structure in the compiler. It is the context that +you use to perform all manner of queries. The struct `TyCtxt` defines a reference to this shared +context: + +```rust,ignore +tcx: TyCtxt<'tcx> +// ---- +// | +// arena lifetime +``` + +As you can see, the `TyCtxt` type takes a lifetime parameter. When you see a reference with a +lifetime like `'tcx`, you know that it refers to arena-allocated data (or data that lives as long as +the arenas, anyhow). + +### A Note On Lifetimes + +The Rust compiler is a fairly large program containing lots of big data +structures (e.g. the AST, HIR, and the type system) and as such, arenas and +references are heavily relied upon to minimize unnecessary memory use. This +manifests itself in the way people can plug into the compiler (i.e. the +[driver](./rustc-driver.md)), preferring a "push"-style API (callbacks) instead +of the more Rust-ic "pull" style (think the `Iterator` trait). + +Thread-local storage and interning are used a lot through the compiler to reduce +duplication while also preventing a lot of the ergonomic issues due to many +pervasive lifetimes. The [`rustc::ty::tls`][tls] module is used to access these +thread-locals, although you should rarely need to touch it. + +[tls]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/tls/index.html diff --git a/src/doc/rustc-guide/src/method-lookup.md b/src/doc/rustc-dev-guide/src/method-lookup.md similarity index 100% rename from src/doc/rustc-guide/src/method-lookup.md rename to src/doc/rustc-dev-guide/src/method-lookup.md diff --git a/src/doc/rustc-guide/src/mir/construction.md b/src/doc/rustc-dev-guide/src/mir/construction.md similarity index 100% rename from src/doc/rustc-guide/src/mir/construction.md rename to src/doc/rustc-dev-guide/src/mir/construction.md diff --git a/src/doc/rustc-guide/src/mir/debugging.md b/src/doc/rustc-dev-guide/src/mir/debugging.md similarity index 100% rename from src/doc/rustc-guide/src/mir/debugging.md rename to src/doc/rustc-dev-guide/src/mir/debugging.md diff --git a/src/doc/rustc-guide/src/mir/index.md b/src/doc/rustc-dev-guide/src/mir/index.md similarity index 87% rename from src/doc/rustc-guide/src/mir/index.md rename to src/doc/rustc-dev-guide/src/mir/index.md index c02b86e9a1..dbc2a316f0 100644 --- a/src/doc/rustc-guide/src/mir/index.md +++ b/src/doc/rustc-dev-guide/src/mir/index.md @@ -84,11 +84,7 @@ with a bunch of variable declarations. They look like this: ```mir let mut _0: (); // return place -scope 1 { - let mut _1: std::vec::Vec; // "vec" in scope 1 at src/main.rs:2:9: 2:16 -} -scope 2 { -} +let mut _1: std::vec::Vec; // in scope 0 at src/main.rs:2:9: 2:16 let mut _2: (); let mut _3: &mut std::vec::Vec; let mut _4: (); @@ -97,11 +93,27 @@ let mut _5: &mut std::vec::Vec; You can see that variables in MIR don't have names, they have indices, like `_0` or `_1`. We also intermingle the user's variables (e.g., -`_1`) with temporary values (e.g., `_2` or `_3`). You can tell the -difference between user-defined variables have a comment that gives -you their original name (`// "vec" in scope 1...`). The "scope" blocks -(e.g., `scope 1 { .. }`) describe the lexical structure of the source -program (which names were in scope when). +`_1`) with temporary values (e.g., `_2` or `_3`). You can tell apart +user-defined variables because they have debuginfo associated to them (see below). + +**User variable debuginfo.** Below the variable declarations, we find the only +hint that `_1` represents a user variable: +```mir +scope 1 { + debug vec => _1; // in scope 1 at src/main.rs:2:9: 2:16 +} +``` +Each `debug => ;` annotation describes a named user variable, +and where (i.e. the place) a debugger can find the data of that variable. +Here the mapping is trivial, but optimizations may complicate the place, +or lead to multiple user variables sharing the same place. +Additionally, closure captures are described using the same system, and so +they're complicated even without optimizations, e.g.: `debug x => (*((*_1).0: &T));`. + +The "scope" blocks (e.g., `scope 1 { .. }`) describe the lexical structure of +the source program (which names were in scope when), so any part of the program +annotated with `// in scope 0` would be missing `vec`, if you were stepping +through the code in a debugger, for example. **Basic blocks.** Reading further, we see our first **basic block** (naturally it may look slightly different when you view it, and I am ignoring some of the diff --git a/src/doc/rustc-guide/src/mir/mir_detailed.dot b/src/doc/rustc-dev-guide/src/mir/mir_detailed.dot similarity index 100% rename from src/doc/rustc-guide/src/mir/mir_detailed.dot rename to src/doc/rustc-dev-guide/src/mir/mir_detailed.dot diff --git a/src/doc/rustc-guide/src/mir/mir_detailed.svg b/src/doc/rustc-dev-guide/src/mir/mir_detailed.svg similarity index 100% rename from src/doc/rustc-guide/src/mir/mir_detailed.svg rename to src/doc/rustc-dev-guide/src/mir/mir_detailed.svg diff --git a/src/doc/rustc-guide/src/mir/mir_overview.dot b/src/doc/rustc-dev-guide/src/mir/mir_overview.dot similarity index 100% rename from src/doc/rustc-guide/src/mir/mir_overview.dot rename to src/doc/rustc-dev-guide/src/mir/mir_overview.dot diff --git a/src/doc/rustc-guide/src/mir/mir_overview.svg b/src/doc/rustc-dev-guide/src/mir/mir_overview.svg similarity index 100% rename from src/doc/rustc-guide/src/mir/mir_overview.svg rename to src/doc/rustc-dev-guide/src/mir/mir_overview.svg diff --git a/src/doc/rustc-guide/src/mir/optimizations.md b/src/doc/rustc-dev-guide/src/mir/optimizations.md similarity index 84% rename from src/doc/rustc-guide/src/mir/optimizations.md rename to src/doc/rustc-dev-guide/src/mir/optimizations.md index f3fdd52f31..03dc219536 100644 --- a/src/doc/rustc-guide/src/mir/optimizations.md +++ b/src/doc/rustc-dev-guide/src/mir/optimizations.md @@ -8,8 +8,8 @@ to do, so compilation is faster. Note that since MIR is generic (not effective; we can optimize the generic version, so all of the monomorphizations are cheaper! -[mir]: https://rust-lang.github.io/rustc-guide/mir/index.html -[monomorph]: https://rust-lang.github.io/rustc-guide/appendix/glossary.html?highlight=monomorphize#appendix-c-glossary +[mir]: https://rustc-dev-guide.rust-lang.org/mir/index.html +[monomorph]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html?highlight=monomorphize#appendix-c-glossary MIR optimizations run after borrow checking. We run a series of optimization passes over the MIR to improve it. Some passes are required to run on all code, @@ -22,9 +22,9 @@ run and that some validation has occurred. Then, it [steals][steal] the MIR optimizes it, and returns the improved MIR. [optmir]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir/transform/fn.optimized_mir.html -[query]: https://rust-lang.github.io/rustc-guide/query.html -[defid]: https://rust-lang.github.io/rustc-guide/appendix/glossary.html?highlight=DefId#appendix-c-glossary -[steal]: https://rust-lang.github.io/rustc-guide/mir/passes.html?highlight=steal#stealing +[query]: https://rustc-dev-guide.rust-lang.org/query.html +[defid]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html?highlight=DefId#appendix-c-glossary +[steal]: https://rustc-dev-guide.rust-lang.org/mir/passes.html?highlight=steal#stealing ## Defining optimization passes diff --git a/src/doc/rustc-guide/src/mir/passes.md b/src/doc/rustc-dev-guide/src/mir/passes.md similarity index 100% rename from src/doc/rustc-guide/src/mir/passes.md rename to src/doc/rustc-dev-guide/src/mir/passes.md diff --git a/src/doc/rustc-guide/src/mir/visitor.md b/src/doc/rustc-dev-guide/src/mir/visitor.md similarity index 100% rename from src/doc/rustc-guide/src/mir/visitor.md rename to src/doc/rustc-dev-guide/src/mir/visitor.md diff --git a/src/doc/rustc-guide/src/miri.md b/src/doc/rustc-dev-guide/src/miri.md similarity index 100% rename from src/doc/rustc-guide/src/miri.md rename to src/doc/rustc-dev-guide/src/miri.md diff --git a/src/doc/rustc-guide/src/name-resolution.md b/src/doc/rustc-dev-guide/src/name-resolution.md similarity index 86% rename from src/doc/rustc-guide/src/name-resolution.md rename to src/doc/rustc-dev-guide/src/name-resolution.md index 3117217e5e..6dfbd91a86 100644 --- a/src/doc/rustc-guide/src/name-resolution.md +++ b/src/doc/rustc-dev-guide/src/name-resolution.md @@ -1,9 +1,26 @@ # Name resolution -The name resolution is a two-phase process. In the first phase, which runs +## Basics + +In our programs we can refer to variables, types, functions, etc, by giving them +a name. These names are not always unique. For example, take this valid Rust +program: + +```rust +type x = u32; +let x: x = 1; +let y: x = 2; +``` + +How do we know on line 3 whether `x` is a type (u32) or a value (1)? These +conflicts are resolved during name resolution. In this specific case, name +resolution defines that type names and variable names live in separate +namespaces and therefore can co-exist. + +The name resolution in Rust is a two-phase process. In the first phase, which runs during macro expansion, we build a tree of modules and resolve imports. Macro expansion and name resolution communicate with each other via the `Resolver` -trait, defined in `libsyntax`. +trait, defined in `librustc_ast`. The input to the second phase is the syntax tree, produced by parsing input files and expanding macros. This phase produces links from all the names in the @@ -20,7 +37,7 @@ The name resolution lives in the `librustc_resolve` crate, with the meat in ## Namespaces -Different kind of symbols live in different namespaces ‒ eg. types don't +Different kind of symbols live in different namespaces ‒ e.g. types don't clash with variables. This usually doesn't happen, because variables start with lower-case letter while types with upper case one, but this is only a convention. This is legal Rust code that'll compile (with warnings): @@ -82,7 +99,7 @@ fn do_something(val: T) { // <- New rib in both types and values (1) Because the rules for different namespaces are a bit different, each namespace has its own independent rib stack that is constructed in parallel to the others. -In addition, there's also a rib stack for local labels (eg. names of loops or +In addition, there's also a rib stack for local labels (e.g. names of loops or blocks), which isn't a full namespace in its own right. ## Overall strategy @@ -112,7 +129,7 @@ Still, it probably provides useful first guidepost to what happens in there. following stages of compilation? * Who calls it and how it is actually used. * Is it a pass and then the result is only used, or can it be computed - incrementally (eg. for RLS)? + incrementally (e.g. for RLS)? * The overall strategy description is a bit vague. * Where does the name `Rib` come from? * Does this thing have its own tests, or is it tested only as part of some e2e diff --git a/src/doc/rustc-guide/src/opaque-types-type-alias-impl-trait.md b/src/doc/rustc-dev-guide/src/opaque-types-type-alias-impl-trait.md similarity index 100% rename from src/doc/rustc-guide/src/opaque-types-type-alias-impl-trait.md rename to src/doc/rustc-dev-guide/src/opaque-types-type-alias-impl-trait.md diff --git a/src/doc/rustc-guide/src/panic-implementation.md b/src/doc/rustc-dev-guide/src/panic-implementation.md similarity index 100% rename from src/doc/rustc-guide/src/panic-implementation.md rename to src/doc/rustc-dev-guide/src/panic-implementation.md diff --git a/src/doc/rustc-guide/src/param_env.md b/src/doc/rustc-dev-guide/src/param_env.md similarity index 100% rename from src/doc/rustc-guide/src/param_env.md rename to src/doc/rustc-dev-guide/src/param_env.md diff --git a/src/doc/rustc-guide/src/part-1-intro.md b/src/doc/rustc-dev-guide/src/part-1-intro.md similarity index 78% rename from src/doc/rustc-guide/src/part-1-intro.md rename to src/doc/rustc-dev-guide/src/part-1-intro.md index 65cb1ae482..7597c71285 100644 --- a/src/doc/rustc-guide/src/part-1-intro.md +++ b/src/doc/rustc-dev-guide/src/part-1-intro.md @@ -1,6 +1,6 @@ # Part 1: Building, debugging, and contributing to Rustc -This section of the rustc-guide contains knowledge that should be useful to you +This section of the rustc-dev-guide contains knowledge that should be useful to you regardless of what part of the compiler you are working on. This includes both technical info and tips (e.g. how to compile and debug the compiler) and info about processes in the Rust project (e.g. stabilization and info about the diff --git a/src/doc/rustc-guide/src/part-2-intro.md b/src/doc/rustc-dev-guide/src/part-2-intro.md similarity index 85% rename from src/doc/rustc-guide/src/part-2-intro.md rename to src/doc/rustc-dev-guide/src/part-2-intro.md index 6dd26f44cc..1a47f21e53 100644 --- a/src/doc/rustc-guide/src/part-2-intro.md +++ b/src/doc/rustc-dev-guide/src/part-2-intro.md @@ -7,6 +7,6 @@ compilation works. This section should be friendly to both readers interested in the end-to-end process of compilation _and_ readers interested in learning about a specific system they wish to contribute to. If anything is unclear, feel free to file -an issue on the [rustc-guide repo](https://github.com/rust-lang/rustc-guide) +an issue on the [rustc-dev-guide repo](https://github.com/rust-lang/rustc-dev-guide) or contact the compiler team, as detailed in [this chapter from Part 1](./compiler-team.md). diff --git a/src/doc/rustc-guide/src/profile-guided-optimization.md b/src/doc/rustc-dev-guide/src/profile-guided-optimization.md similarity index 100% rename from src/doc/rustc-guide/src/profile-guided-optimization.md rename to src/doc/rustc-dev-guide/src/profile-guided-optimization.md diff --git a/src/doc/rustc-guide/src/profiling.md b/src/doc/rustc-dev-guide/src/profiling.md similarity index 100% rename from src/doc/rustc-guide/src/profiling.md rename to src/doc/rustc-dev-guide/src/profiling.md diff --git a/src/doc/rustc-guide/src/profiling/with_perf.md b/src/doc/rustc-dev-guide/src/profiling/with_perf.md similarity index 100% rename from src/doc/rustc-guide/src/profiling/with_perf.md rename to src/doc/rustc-dev-guide/src/profiling/with_perf.md diff --git a/src/doc/rustc-guide/src/queries/example-0.counts.txt b/src/doc/rustc-dev-guide/src/queries/example-0.counts.txt similarity index 100% rename from src/doc/rustc-guide/src/queries/example-0.counts.txt rename to src/doc/rustc-dev-guide/src/queries/example-0.counts.txt diff --git a/src/doc/rustc-guide/src/queries/example-0.html b/src/doc/rustc-dev-guide/src/queries/example-0.html similarity index 100% rename from src/doc/rustc-guide/src/queries/example-0.html rename to src/doc/rustc-dev-guide/src/queries/example-0.html diff --git a/src/doc/rustc-guide/src/queries/example-0.png b/src/doc/rustc-dev-guide/src/queries/example-0.png similarity index 100% rename from src/doc/rustc-guide/src/queries/example-0.png rename to src/doc/rustc-dev-guide/src/queries/example-0.png diff --git a/src/doc/rustc-guide/src/queries/incremental-compilation-in-detail.md b/src/doc/rustc-dev-guide/src/queries/incremental-compilation-in-detail.md similarity index 100% rename from src/doc/rustc-guide/src/queries/incremental-compilation-in-detail.md rename to src/doc/rustc-dev-guide/src/queries/incremental-compilation-in-detail.md diff --git a/src/doc/rustc-guide/src/queries/incremental-compilation.md b/src/doc/rustc-dev-guide/src/queries/incremental-compilation.md similarity index 100% rename from src/doc/rustc-guide/src/queries/incremental-compilation.md rename to src/doc/rustc-dev-guide/src/queries/incremental-compilation.md diff --git a/src/doc/rustc-guide/src/queries/profiling.md b/src/doc/rustc-dev-guide/src/queries/profiling.md similarity index 100% rename from src/doc/rustc-guide/src/queries/profiling.md rename to src/doc/rustc-dev-guide/src/queries/profiling.md diff --git a/src/doc/rustc-guide/src/queries/query-evaluation-model-in-detail.md b/src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md similarity index 99% rename from src/doc/rustc-guide/src/queries/query-evaluation-model-in-detail.md rename to src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md index a1fbed2e54..83c1275509 100644 --- a/src/doc/rustc-guide/src/queries/query-evaluation-model-in-detail.md +++ b/src/doc/rustc-dev-guide/src/queries/query-evaluation-model-in-detail.md @@ -115,7 +115,7 @@ The `type_check_crate` query provider would look something like the following: ```rust,ignore fn type_check_crate_provider(tcx, _key: ()) { - let list_of_items = tcx.hir_map.list_of_items(); + let list_of_hir_items = tcx.hir_map.list_of_items(); for item_def_id in list_of_hir_items { tcx.type_check_item(item_def_id); diff --git a/src/doc/rustc-guide/src/query.md b/src/doc/rustc-dev-guide/src/query.md similarity index 82% rename from src/doc/rustc-guide/src/query.md rename to src/doc/rustc-dev-guide/src/query.md index f5961f6ba7..9ae6baa9e6 100644 --- a/src/doc/rustc-guide/src/query.md +++ b/src/doc/rustc-dev-guide/src/query.md @@ -1,7 +1,7 @@ # Queries: demand-driven compilation As described in [the high-level overview of the compiler][hl], the -Rust compiler is current transitioning from a traditional "pass-based" +Rust compiler is currently transitioning from a traditional "pass-based" setup to a "demand-driven" system. **The Compiler Query System is the key to our new demand-driven organization.** The idea is pretty simple. You have various queries that compute things about the input @@ -76,8 +76,8 @@ dependencies of the local crate). Note that what determines the crate that a query is targeting is not the *kind* of query, but the *key*. For example, when you invoke `tcx.type_of(def_id)`, that could be a local query or an external query, depending on what crate the `def_id` -is referring to (see the `self::keys::Key` trait for more information -on how that works). +is referring to (see the [`self::keys::Key`][Key] trait for more +information on how that works). Providers always have the same signature: @@ -96,8 +96,10 @@ They return the result of the query. #### How providers are setup When the tcx is created, it is given the providers by its creator using -the `Providers` struct. This struct is generated by the macros here, but it -is basically a big list of function pointers: +the [`Providers`][providers_struct] struct. This struct is generated by +the macros here, but it is basically a big list of function pointers: + +[providers_struct]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/query/struct.Providers.html ```rust,ignore struct Providers { @@ -110,11 +112,13 @@ At present, we have one copy of the struct for local crates, and one for external crates, though the plan is that we may eventually have one per crate. -These `Provider` structs are ultimately created and populated by +These `Providers` structs are ultimately created and populated by `librustc_driver`, but it does this by distributing the work throughout the other `rustc_*` crates. This is done by invoking -various `provide` functions. These functions tend to look something -like this: +various [`provide`][provide_fn] functions. These functions tend to look +something like this: + +[provide_fn]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/hir/fn.provide.html ```rust,ignore pub fn provide(providers: &mut Providers) { @@ -147,13 +151,16 @@ fn fubar<'tcx>(tcx: TyCtxt<'tcx>, key: DefId) -> Fubar<'tcx> { ... } N.B. Most of the `rustc_*` crates only provide **local providers**. Almost all **extern providers** wind up going through the -[`rustc_metadata` crate][rustc_metadata], which loads the information from the -crate metadata. But in some cases there are crates that provide queries for -*both* local and external crates, in which case they define both a -`provide` and a `provide_extern` function that `rustc_driver` can -invoke. +[`rustc_metadata` crate][rustc_metadata], which loads the information +from the crate metadata. But in some cases there are crates that +provide queries for *both* local and external crates, in which case +they define both a [`provide`][ext_provide] and a +[`provide_extern`][ext_provide_extern] function that `rustc_driver` +can invoke. [rustc_metadata]: https://github.com/rust-lang/rust/tree/master/src/librustc_metadata +[ext_provide]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_llvm/attributes/fn.provide.html +[ext_provide_extern]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_llvm/attributes/fn.provide_extern.html ### Adding a new kind of query @@ -205,7 +212,7 @@ Let's go over them one by one: (`ty::queries::type_of`) that will be generated to represent this query. - **Query key type:** the type of the argument to this query. - This type must implement the `ty::query::keys::Key` trait, which + This type must implement the [`ty::query::keys::Key`][Key] trait, which defines (for example) how to map it to a crate, and so forth. - **Result type of query:** the type produced by this query. This type should (a) not use `RefCell` or other interior mutability and (b) be @@ -218,6 +225,8 @@ Let's go over them one by one: - **Query modifiers:** various flags and options that customize how the query is processed. +[Key]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/query/keys/trait.Key.html + So, to add a query: - Add an entry to `rustc_queries!` using the format above. @@ -229,7 +238,7 @@ So, to add a query: For each kind, the `rustc_queries` macro will generate a "query struct" named after the query. This struct is a kind of a place-holder describing the query. Each such struct implements the -`self::config::QueryConfig` trait, which has associated types for the +[`self::config::QueryConfig`][QueryConfig] trait, which has associated types for the key/value of that particular query. Basically the code generated looks something like this: @@ -247,13 +256,16 @@ impl<'tcx> QueryConfig for type_of<'tcx> { ``` There is an additional trait that you may wish to implement called -`self::config::QueryDescription`. This trait is used during cycle -errors to give a "human readable" name for the query, so that we can -summarize what was happening when the cycle occurred. Implementing -this trait is optional if the query key is `DefId`, but if you *don't* -implement it, you get a pretty generic error ("processing `foo`..."). +[`self::config::QueryDescription`][QueryDescription]. This trait is +used during cycle errors to give a "human readable" name for the query, +so that we can summarize what was happening when the cycle occurred. +Implementing this trait is optional if the query key is `DefId`, but +if you *don't* implement it, you get a pretty generic error ("processing `foo`..."). You can put new impls into the `config` module. They look something like this: +[QueryConfig]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/query/trait.QueryConfig.html +[QueryDescription]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/query/config/trait.QueryDescription.html + ```rust,ignore impl<'tcx> QueryDescription for queries::type_of<'tcx> { fn describe(tcx: TyCtxt, key: DefId) -> String { diff --git a/src/doc/rustc-guide/src/rustc-driver.md b/src/doc/rustc-dev-guide/src/rustc-driver.md similarity index 80% rename from src/doc/rustc-guide/src/rustc-driver.md rename to src/doc/rustc-dev-guide/src/rustc-driver.md index 50c7b2731a..e240ea58b2 100644 --- a/src/doc/rustc-guide/src/rustc-driver.md +++ b/src/doc/rustc-dev-guide/src/rustc-driver.md @@ -32,19 +32,6 @@ replaces this functionality. > **Warning:** By its very nature, the internal compiler APIs are always going > to be unstable. That said, we do try not to break things unnecessarily. -## A Note On Lifetimes - -The Rust compiler is a fairly large program containing lots of big data -structures (e.g. the AST, HIR, and the type system) and as such, arenas and -references are heavily relied upon to minimize unnecessary memory use. This -manifests itself in the way people can plug into the compiler, preferring a -"push"-style API (callbacks) instead of the more Rust-ic "pull" style (think -the `Iterator` trait). - -Thread-local storage and interning are used a lot through the compiler to reduce -duplication while also preventing a lot of the ergonomic issues due to many -pervasive lifetimes. The `rustc::ty::tls` module is used to access these -thread-locals, although you should rarely need to touch it. [cb]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_driver/trait.Callbacks.html [rd_rc]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_driver/fn.run_compiler.html diff --git a/src/doc/rustc-guide/src/rustdoc.md b/src/doc/rustc-dev-guide/src/rustdoc.md similarity index 100% rename from src/doc/rustc-guide/src/rustdoc.md rename to src/doc/rustc-dev-guide/src/rustdoc.md diff --git a/src/doc/rustc-guide/src/salsa.md b/src/doc/rustc-dev-guide/src/salsa.md similarity index 100% rename from src/doc/rustc-guide/src/salsa.md rename to src/doc/rustc-dev-guide/src/salsa.md diff --git a/src/doc/rustc-dev-guide/src/sanitizers.md b/src/doc/rustc-dev-guide/src/sanitizers.md new file mode 100644 index 0000000000..5e1f396f51 --- /dev/null +++ b/src/doc/rustc-dev-guide/src/sanitizers.md @@ -0,0 +1,74 @@ +# Sanitizers Support + +The rustc compiler contains support for following sanitizers: + +* [AddressSanitizer][clang-asan] a faster memory error detector. Can + detect out-of-bounds access to heap, stack, and globals, use after free, use + after return, double free, invalid free, memory leaks. +* [LeakSanitizer][clang-lsan] a run-time memory leak detector. +* [MemorySanitizer][clang-msan] a detector of uninitialized reads. +* [ThreadSanitizer][clang-tsan] a fast data race detector. + +## How to use the sanitizers? + +To enable a sanitizer compile with `-Zsanitizer=...` option, where value is one +of `address`, `leak`, `memory` or `thread`. For more details how to use +sanitizers please refer to [the unstable book](https://doc.rust-lang.org/unstable-book/). + +## How are sanitizers implemented in rustc? + +The implementation of sanitizers relies almost entirely on LLVM. The rustc is +an integration point for LLVM compile time instrumentation passes and runtime +libraries. Highlight of the most important aspects of the implementation: + +* The sanitizer runtime libraries are part of the [compiler-rt] project, and + [will be built on supported targets][sanitizer-build] when enabled in `config.toml`: + + ```toml + [build] + sanitizers = true + ``` + + The runtimes are [placed into target libdir][sanitizer-copy]. + +* During LLVM code generation, the functions intended for instrumentation are + [marked][sanitizer-attribute] with appropriate LLVM attribute: + `SanitizeAddress`, `SanitizeMemory`, or `SanitizeThread`. By default all + functions are instrumented, but this behaviour can be changed with + `#[no_sanitize(...)]`. + +* The decision whether to perform instrumentation or not is possible only at a + function granularity. In the cases were those decision differ between + functions it might be necessary to inhibit inlining, both at [MIR + level][inline-mir] and [LLVM level][inline-llvm]. + +* The LLVM IR generated by rustc is instrumented by [dedicated LLVM + passes][sanitizer-pass], different for each sanitizer. Instrumentation + passes are invoked after optimization passes. + +* When producing an executable, the sanitizer specific runtime library is + [linked in][sanitizer-link]. The libraries are searched for in target libdir + relative to default system root, so that this process is not affected + by sysroot overrides used for example by cargo `-Zbuild-std` functionality. + +[compiler-rt]: https://github.com/llvm/llvm-project/tree/master/compiler-rt +[sanitizer-build]: https://github.com/rust-lang/rust/blob/a29424a2265411dda7d7446516ac5fd7499e2b55/src/bootstrap/native.rs#L566-L624 +[sanitizer-copy]: https://github.com/rust-lang/rust/blob/a29424a2265411dda7d7446516ac5fd7499e2b55/src/bootstrap/compile.rs#L270-L304 +[sanitizer-attribute]: https://github.com/rust-lang/rust/blob/a29424a2265411dda7d7446516ac5fd7499e2b55/src/librustc_codegen_llvm/attributes.rs#L49-L72 +[inline-mir]: https://github.com/rust-lang/rust/blob/a29424a2265411dda7d7446516ac5fd7499e2b55/src/librustc_mir/transform/inline.rs#L232-L252 +[inline-llvm]: https://github.com/rust-lang/llvm-project/blob/9330ec5a4c1df5fc1fa62f993ed6a04da68cb040/llvm/include/llvm/IR/Attributes.td#L225-L241 +[sanitizer-pass]: https://github.com/rust-lang/rust/blob/a29424a2265411dda7d7446516ac5fd7499e2b55/src/librustc_codegen_llvm/back/write.rs#L454-L475 +[sanitizer-link]: https://github.com/rust-lang/rust/blob/a29424a2265411dda7d7446516ac5fd7499e2b55/src/librustc_codegen_ssa/back/link.rs#L748-L787 + +## Additional Information + +* [Sanitizers project page](https://github.com/google/sanitizers/wiki/) +* [AddressSanitizer in Clang][clang-asan] +* [LeakSanitizer in Clang][clang-lsan] +* [MemorySanitizer in Clang][clang-msan] +* [ThreadSanitizer in Clang][clang-tsan] + +[clang-asan]: https://clang.llvm.org/docs/AddressSanitizer.html +[clang-lsan]: https://clang.llvm.org/docs/LeakSanitizer.html +[clang-msan]: https://clang.llvm.org/docs/MemorySanitizer.html +[clang-tsan]: https://clang.llvm.org/docs/ThreadSanitizer.html diff --git a/src/doc/rustc-guide/src/stability.md b/src/doc/rustc-dev-guide/src/stability.md similarity index 100% rename from src/doc/rustc-guide/src/stability.md rename to src/doc/rustc-dev-guide/src/stability.md diff --git a/src/doc/rustc-guide/src/stabilization_guide.md b/src/doc/rustc-dev-guide/src/stabilization_guide.md similarity index 100% rename from src/doc/rustc-guide/src/stabilization_guide.md rename to src/doc/rustc-dev-guide/src/stabilization_guide.md diff --git a/src/doc/rustc-guide/src/test-implementation.md b/src/doc/rustc-dev-guide/src/test-implementation.md similarity index 90% rename from src/doc/rustc-guide/src/test-implementation.md rename to src/doc/rustc-dev-guide/src/test-implementation.md index 59cc7c5bdd..e5bcedf136 100644 --- a/src/doc/rustc-guide/src/test-implementation.md +++ b/src/doc/rustc-dev-guide/src/test-implementation.md @@ -31,14 +31,14 @@ How does any sort of `main` function invoke these tests if they're not visible? What exactly is `rustc --test` doing? `#[test]` is implemented as a syntactic transformation inside the compiler's -[`libsyntax` crate][libsyntax]. Essentially, it's a fancy macro, that +[`librustc_ast` crate][librustc_ast]. Essentially, it's a fancy macro, that rewrites the crate in 3 steps: #### Step 1: Re-Exporting As mentioned earlier, tests can exist inside private modules, so we need a way of exposing them to the main function, without breaking any existing -code. To that end, `libsyntax` will create local modules called +code. To that end, `librustc_ast` will create local modules called `__test_reexports` that recursively reexport tests. This expansion translates the above example into: @@ -78,7 +78,7 @@ hygiene. #### Step 2: Harness Generation Now that our tests are accessible from the root of our crate, we need to do -something with them. `libsyntax` generates a module like so: +something with them. `librustc_ast` generates a module like so: ```rust,ignore #[main] @@ -115,7 +115,7 @@ fn foo() { This means our tests are more than just simple functions, they have configuration information as well. `test` encodes this configuration data into a struct called [`TestDesc`][TestDesc]. For each test function in a -crate, `libsyntax` will parse its attributes and generate a `TestDesc` +crate, `librustc_ast` will parse its attributes and generate a `TestDesc` instance. It then combines the `TestDesc` and test function into the predictably named `TestDescAndFn` struct, that `test_main_static` operates on. For a given test, the generated `TestDescAndFn` instance looks like so: @@ -146,7 +146,7 @@ $ rustc my_mod.rs -Z unpretty=hir [test]: https://doc.rust-lang.org/test/index.html [TestDesc]: https://doc.rust-lang.org/test/struct.TestDesc.html -[Symbol]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/struct.Ident.html -[Ident]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/struct.Ident.html +[Symbol]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/struct.Ident.html +[Ident]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/struct.Ident.html [eRFC]: https://github.com/rust-lang/rfcs/blob/master/text/2318-custom-test-frameworks.md -[libsyntax]: https://github.com/rust-lang/rust/tree/master/src/libsyntax +[librustc_ast]: https://github.com/rust-lang/rust/tree/master/src/librustc_ast diff --git a/src/doc/rustc-guide/src/tests/adding.md b/src/doc/rustc-dev-guide/src/tests/adding.md similarity index 95% rename from src/doc/rustc-guide/src/tests/adding.md rename to src/doc/rustc-dev-guide/src/tests/adding.md index 8492cbbcc9..dadd8e2c15 100644 --- a/src/doc/rustc-guide/src/tests/adding.md +++ b/src/doc/rustc-dev-guide/src/tests/adding.md @@ -150,7 +150,7 @@ source. compares against `.fixed` (they must match). Finally, the fixed source is compiled, and this compilation is required to succeed. The `.fixed` file can also be generated automatically with the - `--bless` option, discussed [below](#bless). + `--bless` option, described in [this section][bless]. * `min-gdb-version` specifies the minimum gdb version required for this test; see also `ignore-gdb-version` * `min-lldb-version` specifies the minimum lldb version required for @@ -185,6 +185,7 @@ source. have a gate test. [`header.rs`]: https://github.com/rust-lang/rust/tree/master/src/tools/compiletest/src/header.rs +[bless]: ./running.md#editing-and-updating-the-reference-files @@ -284,22 +285,6 @@ you can even run the resulting program. Just add one of the following - `// run-pass` – compilation should succeed and we should run the resulting binary - - -### Editing and updating the reference files - -If you have changed the compiler's output intentionally, or you are -making a new test, you can pass `--bless` to the test subcommand. E.g. -if some tests in `src/test/ui` are failing, you can run - -```text -./x.py test --stage 1 src/test/ui --bless -``` - -to automatically adjust the `.stderr`, `.stdout` or `.fixed` files of -all tests. Of course you can also target just specific tests with the -`--test-args your_test_name` flag, just like when running the tests. - ### Normalization The normalization applied is aimed at eliminating output difference diff --git a/src/doc/rustc-guide/src/tests/intro.md b/src/doc/rustc-dev-guide/src/tests/intro.md similarity index 95% rename from src/doc/rustc-guide/src/tests/intro.md rename to src/doc/rustc-dev-guide/src/tests/intro.md index 4572d23ca9..6a528ae457 100644 --- a/src/doc/rustc-guide/src/tests/intro.md +++ b/src/doc/rustc-dev-guide/src/tests/intro.md @@ -61,7 +61,20 @@ including: There is more information in the [section on coding conventions](../conventions.html#formatting). - Example: `./x.py test src/tools/tidy` + Example: `./x.py test tidy` + +- **Formatting** – Rustfmt is integrated with the build system to enforce + uniform style across the compiler. In the CI, we check that the formatting + is correct. The formatting check is also automatically run by the Tidy tool + mentioned above. + + Example: `./x.py fmt --check` checks formatting an exits with an error if + formatting is needed. + + Example: `./x.py fmt` runs rustfmt on the codebase. + + Example: `./x.py test tidy --bless` does formatting before doing + other tidy checks. - **Unit tests** – The Rust standard library and many of the Rust packages include typical Rust `#[test]` unittests. Under the hood, `x.py` will run diff --git a/src/doc/rustc-guide/src/tests/running.md b/src/doc/rustc-dev-guide/src/tests/running.md similarity index 89% rename from src/doc/rustc-guide/src/tests/running.md rename to src/doc/rustc-dev-guide/src/tests/running.md index 4a86d2cce8..f5c9bdb721 100644 --- a/src/doc/rustc-guide/src/tests/running.md +++ b/src/doc/rustc-dev-guide/src/tests/running.md @@ -63,7 +63,7 @@ Likewise, you can test a single file by passing its path: ### Run only the tidy script ```bash -./x.py test src/tools/tidy +./x.py test tidy ``` ### Run tests on the standard library @@ -72,10 +72,10 @@ Likewise, you can test a single file by passing its path: ./x.py test src/libstd ``` -### Run tests on the standard library and run the tidy script +### Run the tidy script and tests on the standard library ```bash -./x.py test src/libstd src/tools/tidy +./x.py test tidy src/libstd ``` ### Run tests on the standard library using a stage 1 compiler @@ -108,6 +108,20 @@ Under the hood, the test runner invokes the standard rust test runner filtering for tests that include "issue-1234" in the name. (Thus `--test-args` is a good way to run a collection of related tests.) +## Editing and updating the reference files + +If you have changed the compiler's output intentionally, or you are +making a new test, you can pass `--bless` to the test subcommand. E.g. +if some tests in `src/test/ui` are failing, you can run + +```text +./x.py test --stage 1 src/test/ui --bless +``` + +to automatically adjust the `.stderr`, `.stdout` or `.fixed` files of +all tests. Of course you can also target just specific tests with the +`--test-args your_test_name` flag, just like when running the tests. + ## Passing `--pass $mode` Pass UI tests now have three modes, `check-pass`, `build-pass` and diff --git a/src/doc/rustc-guide/src/the-parser.md b/src/doc/rustc-dev-guide/src/the-parser.md similarity index 86% rename from src/doc/rustc-guide/src/the-parser.md rename to src/doc/rustc-dev-guide/src/the-parser.md index 3584d73e44..8b8ef77cd7 100644 --- a/src/doc/rustc-guide/src/the-parser.md +++ b/src/doc/rustc-dev-guide/src/the-parser.md @@ -18,7 +18,7 @@ form which is easier for the compiler to work with, usually called an [*Abstract Syntax Tree*][ast] (AST). An AST mirrors the structure of a Rust program in memory, using a `Span` to link a particular AST node back to its source text. -The AST is defined in [`libsyntax`][libsyntax], along with some definitions for +The AST is defined in [`librustc_ast`][librustc_ast], along with some definitions for tokens and token streams, data structures/traits for mutating ASTs, and shared definitions for other AST-related parts of the compiler (like the lexer and macro-expansion). @@ -46,18 +46,18 @@ Code for lexical analysis is split between two crates: constituting tokens. Although it is popular to implement lexers as generated finite state machines, the lexer in `rustc_lexer` is hand-written. -- [`StringReader`] from [libsyntax] integrates `rustc_lexer` with `rustc` +- [`StringReader`] from [`librustc_ast`][librustc_ast] integrates `rustc_lexer` with `rustc` specific data structures. Specifically, it adds `Span` information to tokens returned by `rustc_lexer` and interns identifiers. -[libsyntax]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/index.html +[librustc_ast]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/index.html [rustc_errors]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/index.html [ast]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [`SourceMap`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/source_map/struct.SourceMap.html -[ast module]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/ast/index.html +[ast module]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/ast/index.html [librustc_parse]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse/index.html [parser]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse/parser/index.html -[`Parser`]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/parse/parser/struct.Parser.html +[`Parser`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/parse/parser/struct.Parser.html [`StringReader`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse/lexer/struct.StringReader.html -[visit module]: https://doc.rust-lang.org/nightly/nightly-rustc/syntax/visit/index.html +[visit module]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_ast/visit/index.html [sourcefile]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.SourceFile.html diff --git a/src/doc/rustc-guide/src/traits/associated-types.md b/src/doc/rustc-dev-guide/src/traits/associated-types.md similarity index 100% rename from src/doc/rustc-guide/src/traits/associated-types.md rename to src/doc/rustc-dev-guide/src/traits/associated-types.md diff --git a/src/doc/rustc-guide/src/traits/bibliography.md b/src/doc/rustc-dev-guide/src/traits/bibliography.md similarity index 100% rename from src/doc/rustc-guide/src/traits/bibliography.md rename to src/doc/rustc-dev-guide/src/traits/bibliography.md diff --git a/src/doc/rustc-guide/src/traits/caching.md b/src/doc/rustc-dev-guide/src/traits/caching.md similarity index 100% rename from src/doc/rustc-guide/src/traits/caching.md rename to src/doc/rustc-dev-guide/src/traits/caching.md diff --git a/src/doc/rustc-guide/src/traits/canonical-queries.md b/src/doc/rustc-dev-guide/src/traits/canonical-queries.md similarity index 100% rename from src/doc/rustc-guide/src/traits/canonical-queries.md rename to src/doc/rustc-dev-guide/src/traits/canonical-queries.md diff --git a/src/doc/rustc-guide/src/traits/canonicalization.md b/src/doc/rustc-dev-guide/src/traits/canonicalization.md similarity index 100% rename from src/doc/rustc-guide/src/traits/canonicalization.md rename to src/doc/rustc-dev-guide/src/traits/canonicalization.md diff --git a/src/doc/rustc-guide/src/traits/chalk-overview.md b/src/doc/rustc-dev-guide/src/traits/chalk-overview.md similarity index 99% rename from src/doc/rustc-guide/src/traits/chalk-overview.md rename to src/doc/rustc-dev-guide/src/traits/chalk-overview.md index a33cbcc63a..88ae7b5a23 100644 --- a/src/doc/rustc-guide/src/traits/chalk-overview.md +++ b/src/doc/rustc-dev-guide/src/traits/chalk-overview.md @@ -226,7 +226,7 @@ Likewise, lowering tests use the [`lowering_success!` and [ast]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [chalk]: https://github.com/rust-lang/chalk -[rustc-issues]: https://github.com/rust-lang/rustc-guide/issues +[rustc-issues]: https://github.com/rust-lang/rustc-dev-guide/issues [universal quantification]: https://en.wikipedia.org/wiki/Universal_quantification [`ProgramClause`]: https://rust-lang.github.io/chalk/chalk_ir/enum.ProgramClause.html diff --git a/src/doc/rustc-guide/src/traits/goals-and-clauses.md b/src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md similarity index 100% rename from src/doc/rustc-guide/src/traits/goals-and-clauses.md rename to src/doc/rustc-dev-guide/src/traits/goals-and-clauses.md diff --git a/src/doc/rustc-guide/src/traits/hrtb.md b/src/doc/rustc-dev-guide/src/traits/hrtb.md similarity index 97% rename from src/doc/rustc-guide/src/traits/hrtb.md rename to src/doc/rustc-dev-guide/src/traits/hrtb.md index 8b3a9f649b..f41d43ffd3 100644 --- a/src/doc/rustc-guide/src/traits/hrtb.md +++ b/src/doc/rustc-dev-guide/src/traits/hrtb.md @@ -40,8 +40,8 @@ subtyping, we recommend you read the paper). There are a few parts: 2. Match the impl against the [placeholder] obligation. 3. Check for _placeholder leaks_. +[hrsubtype]: ./hrtb.md [placeholder]: ../appendix/glossary.html#appendix-c-glossary -[hrsubtype]: https://github.com/rust-lang/rust/tree/master/src/librustc/infer/higher_ranked/README.md [paper by SPJ]: http://research.microsoft.com/en-us/um/people/simonpj/papers/higher-rank/ So let's work through our example. diff --git a/src/doc/rustc-guide/src/traits/implied-bounds.md b/src/doc/rustc-dev-guide/src/traits/implied-bounds.md similarity index 100% rename from src/doc/rustc-guide/src/traits/implied-bounds.md rename to src/doc/rustc-dev-guide/src/traits/implied-bounds.md diff --git a/src/doc/rustc-guide/src/traits/index.md b/src/doc/rustc-dev-guide/src/traits/index.md similarity index 100% rename from src/doc/rustc-guide/src/traits/index.md rename to src/doc/rustc-dev-guide/src/traits/index.md diff --git a/src/doc/rustc-dev-guide/src/traits/lowering-module.md b/src/doc/rustc-dev-guide/src/traits/lowering-module.md new file mode 100644 index 0000000000..3c5bd7be5d --- /dev/null +++ b/src/doc/rustc-dev-guide/src/traits/lowering-module.md @@ -0,0 +1,56 @@ +# The lowering module in rustc + +The program clauses described in the +[lowering rules](./lowering-rules.html) section are actually +created in the [`rustc_traits::lowering`][lowering] module. + +[lowering]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_traits/lowering/ + +## The `program_clauses_for` query + +The main entry point is the `program_clauses_for` [query], which – +given a `DefId` – produces a set of Chalk program clauses. The +query is invoked on a `DefId` that identifies something like a trait, +an impl, or an associated item definition. It then produces and +returns a vector of program clauses. + +[query]: ../query.html + +## Unit tests + +**Note: We've removed the Chalk unit tests in [rust-lang/rust#69247]. +They will come back once we're ready to integrate next Chalk into rustc.** + +Here's a good example test. At the time of +this writing, it looked like this: + +```rust,ignore +#![feature(rustc_attrs)] + +trait Foo { } + +#[rustc_dump_program_clauses] //~ ERROR program clause dump +impl Foo for T where T: Iterator { } + +fn main() { + println!("hello"); +} +``` + +The `#[rustc_dump_program_clauses]` annotation can be attached to +anything with a `DefId` (It requires the `rustc_attrs` feature). The +compiler will then invoke the `program_clauses_for` query on that +item, and emit compiler errors that dump the clauses produced. These +errors just exist for unit-testing. The stderr will be: + +```text +error: program clause dump + --> $DIR/lower_impl.rs:5:1 + | +LL | #[rustc_dump_program_clauses] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: forall { Implemented(T: Foo) :- ProjectionEq(::Item == i32), TypeOutlives(T: 'static), Implemented(T: std::iter::Iterator), Implemented(T: std::marker::Sized). } +``` + +[rust-lang/rust#69247]: https://github.com/rust-lang/rust/pull/69247 diff --git a/src/doc/rustc-guide/src/traits/lowering-rules.md b/src/doc/rustc-dev-guide/src/traits/lowering-rules.md similarity index 100% rename from src/doc/rustc-guide/src/traits/lowering-rules.md rename to src/doc/rustc-dev-guide/src/traits/lowering-rules.md diff --git a/src/doc/rustc-guide/src/traits/lowering-to-logic.md b/src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md similarity index 100% rename from src/doc/rustc-guide/src/traits/lowering-to-logic.md rename to src/doc/rustc-dev-guide/src/traits/lowering-to-logic.md diff --git a/src/doc/rustc-guide/src/traits/regions.md b/src/doc/rustc-dev-guide/src/traits/regions.md similarity index 100% rename from src/doc/rustc-guide/src/traits/regions.md rename to src/doc/rustc-dev-guide/src/traits/regions.md diff --git a/src/doc/rustc-guide/src/traits/resolution.md b/src/doc/rustc-dev-guide/src/traits/resolution.md similarity index 100% rename from src/doc/rustc-guide/src/traits/resolution.md rename to src/doc/rustc-dev-guide/src/traits/resolution.md diff --git a/src/doc/rustc-guide/src/traits/slg.md b/src/doc/rustc-dev-guide/src/traits/slg.md similarity index 100% rename from src/doc/rustc-guide/src/traits/slg.md rename to src/doc/rustc-dev-guide/src/traits/slg.md diff --git a/src/doc/rustc-guide/src/traits/specialization.md b/src/doc/rustc-dev-guide/src/traits/specialization.md similarity index 100% rename from src/doc/rustc-guide/src/traits/specialization.md rename to src/doc/rustc-dev-guide/src/traits/specialization.md diff --git a/src/doc/rustc-guide/src/traits/wf.md b/src/doc/rustc-dev-guide/src/traits/wf.md similarity index 100% rename from src/doc/rustc-guide/src/traits/wf.md rename to src/doc/rustc-dev-guide/src/traits/wf.md diff --git a/src/doc/rustc-dev-guide/src/ty-fold.md b/src/doc/rustc-dev-guide/src/ty-fold.md new file mode 100644 index 0000000000..e144767dcb --- /dev/null +++ b/src/doc/rustc-dev-guide/src/ty-fold.md @@ -0,0 +1,105 @@ +# `TypeFoldable` and `TypeFolder` + +How is this `subst` query actually implemented? As you can imagine, we might want to do +substitutions on a lot of different things. For example, we might want to do a substitution directly +on a type like we did with `Vec` above. But we might also have a more complex type with other types +nested inside that also need substitutions. + +The answer is a couple of traits: +[`TypeFoldable`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/fold/trait.TypeFoldable.html) +and +[`TypeFolder`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/fold/trait.TypeFolder.html). + +- `TypeFoldable` is implemented by types that embed type information. It allows you to recursively + process the contents of the `TypeFoldable` and do stuff to them. +- `TypeFolder` defines what you want to do with the types you encounter while processing the + `TypeFoldable`. + +For example, the `TypeFolder` trait has a method +[`fold_ty`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/fold/trait.TypeFolder.html#method.fold_ty) +that takes a type as input a type and returns a new type as a result. `TypeFoldable` invokes the +`TypeFolder` `fold_foo` methods on itself, giving the `TypeFolder` access to its contents (the +types, regions, etc that are contained within). + +You can think of it with this analogy to the iterator combinators we have come to love in rust: + +```rust,ignore +vec.iter().map(|e1| foo(e2)).collect() +// ^^^^^^^^^^^^ analogous to `TypeFolder` +// ^^^ analogous to `TypeFoldable` +``` + +So to reiterate: + +- `TypeFolder` is a trait that defines a “map” operation. +- `TypeFoldable` is a trait that is implemented by things that embed types. + +In the case of `subst`, we can see that it is implemented as a `TypeFolder`: +[`SubstFolder`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/struct.SubstFolder.html). +Looking at its implementation, we see where the actual substitutions are happening. + +However, you might also notice that the implementation calls this `super_fold_with` method. What is +that? It is a method of `TypeFoldable`. Consider the following `TypeFoldable` type `MyFoldable`: + +```rust,ignore +struct MyFoldable<'tcx> { + def_id: DefId, + ty: Ty<'tcx>, +} +``` + +The `TypeFolder` can call `super_fold_with` on `MyFoldable` if it just wants to replace some of the +fields of `MyFoldable` with new values. If it instead wants to replace the whole `MyFoldable` with a +different one, it would call `fold_with` instead (a different method on `TypeFoldable`). + +In almost all cases, we don’t want to replace the whole struct; we only want to replace `ty::Ty`s in +the struct, so usually we call `super_fold_with`. A typical implementation that `MyFoldable` could +have might do something like this: + +```rust,ignore +my_foldable: MyFoldable<'tcx> +my_foldable.subst(..., subst) + +impl TypeFoldable for MyFoldable { + fn super_fold_with(&self, folder: &mut impl TypeFolder<'tcx>) -> MyFoldable { + MyFoldable { + def_id: self.def_id.fold_with(folder), + ty: self.ty.fold_with(folder), + } + } + + fn super_visit_with(..) { } +} +``` + +Notice that here, we implement `super_fold_with` to go over the fields of `MyFoldable` and call +`fold_with` on *them*. That is, a folder may replace `def_id` and `ty`, but not the whole +`MyFoldable` struct. + +Here is another example to put things together: suppose we have a type like `Vec>`. The +`ty::Ty` would look like: `Adt(Vec, &[Adt(Vec, &[Param(X)])])`. If we want to do `subst(X => u32)`, +then we would first look at the overall type. We would see that there are no substitutions to be +made at the outer level, so we would descend one level and look at `Adt(Vec, &[Param(X)])`. There +are still no substitutions to be made here, so we would descend again. Now we are looking at +`Param(X)`, which can be substituted, so we replace it with `u32`. We can’t descend any more, so we +are done, and the overall result is `Adt(Vec, &[Adt(Vec, &[u32])])`. + +One last thing to mention: often when folding over a `TypeFoldable`, we don’t want to change most +things. We only want to do something when we reach a type. That means there may be a lot of +`TypeFoldable` types whose implementations basically just forward to their fields’ `TypeFoldable` +implementations. Such implementations of `TypeFoldable` tend to be pretty tedious to write by hand. +For this reason, there is a `derive` macro that allows you to `#![derive(TypeFoldable)]`. It is +defined +[here](https://github.com/rust-lang/rust/blob/master/src/librustc_macros/src/type_foldable.rs). + +**`subst`** In the case of substitutions the [actual +folder](https://github.com/rust-lang/rust/blob/04e69e4f4234beb4f12cc76dcc53e2cc4247a9be/src/librustc/ty/subst.rs#L467-L482) +is going to be doing the indexing we’ve already mentioned. There we define a `Folder` and call +`fold_with` on the `TypeFoldable` to process yourself. Then +[fold_ty](https://github.com/rust-lang/rust/blob/04e69e4f4234beb4f12cc76dcc53e2cc4247a9be/src/librustc/ty/subst.rs#L545-L573) +the method that process each type it looks for a `ty::Param` and for those it replaces it for +something from the list of substitutions, otherwise recursively process the type. To replace it, +calls +[ty_for_param](https://github.com/rust-lang/rust/blob/04e69e4f4234beb4f12cc76dcc53e2cc4247a9be/src/librustc/ty/subst.rs#L589-L624) +and all that does is index into the list of substitutions with the index of the `Param`. + diff --git a/src/doc/rustc-dev-guide/src/ty.md b/src/doc/rustc-dev-guide/src/ty.md new file mode 100644 index 0000000000..bb2c24b13b --- /dev/null +++ b/src/doc/rustc-dev-guide/src/ty.md @@ -0,0 +1,331 @@ +--- +tags: rustc, ty +--- + +# The `ty` module: representing types + +The `ty` module defines how the Rust compiler represents types internally. It also defines the +*typing context* (`tcx` or `TyCtxt`), which is the central data structure in the compiler. + +## `ty::Ty` + +When we talk about how rustc represents types, we usually refer to a type called `Ty` . There are +quite a few modules and types for `Ty` in the compiler ([Ty documentation][ty]). + +[ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/index.html + +The specific `Ty` we are referring to is [`rustc::ty::Ty`][ty_ty] (and not +[`rustc_hir::Ty`][hir_ty]). The distinction is important, so we will discuss it first before going +into the details of `ty::Ty`. + +[ty_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/type.Ty.html +[hir_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/struct.Ty.html + +## `rustc_hir::Ty` vs `ty::Ty` + +The HIR in rustc can be thought of as the high-level intermediate representation. It is more or less +the AST (see [this chapter](hir.md)) as it represents the +syntax that the user wrote, and is obtained after parsing and some *desugaring*. It has a +representation of types, but in reality it reflects more of what the user wrote, that is, what they +wrote so as to represent that type. + +In contrast, `ty::Ty` represents the semantics of a type, that is, the *meaning* of what the user +wrote. For example, `rustc_hir::Ty` would record the fact that a user used the name `u32` twice +in their program, but the `ty::Ty` would record the fact that both usages refer to the same type. + +**Example: `fn foo(x: u32) → u32 { }`** In this function we see that `u32` appears twice. We know +that that is the same type, i.e. the function takes an argument and returns an argument of the same +type, but from the point of view of the HIR there would be two distinct type instances because these +are occurring in two different places in the program. That is, they have two +different [`Span`s][span] (locations). + +[span]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html + +**Example: `fn foo(x: &u32) -> &u32)`** In addition, HIR might have information left out. This type +`&u32` is incomplete, since in the full rust type there is actually a lifetime, but we didn’t need +to write those lifetimes. There are also some elision rules that insert information. The result may +look like `fn foo<'a>(x: &'a u32) -> &'a u32)`. + +In the HIR level, these things are not spelled out and you can say the picture is rather incomplete. +However, at the `ty::Ty` level, these details are added and it is complete. Moreover, we will have +exactly one `ty::Ty` for a given type, like `u32`, and that `ty::Ty` is used for all `u32`s in the +whole program, not a specific usage, unlike `rustc_hir::Ty`. + +Here is a summary: + +| [`rustc_hir::Ty`][hir_ty] | [`ty::Ty`][ty_ty] | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Describe the *syntax* of a type: what the user wrote (with some desugaring). | Describe the *semantics* of a type: the meaning of what the user wrote. | +| Each `rustc_hir::Ty` has its own spans corresponding to the appropriate place in the program. | Doesn’t correspond to a single place in the user’s program. | +| `rustc_hir::Ty` has generics and lifetimes; however, some of those lifetimes are special markers like [`LifetimeName::Implicit`][implicit]. | `ty::Ty` has the full type, including generics and lifetimes, even if the user left them out | +| `fn foo(x: u32) → u32 { }` - Two `rustc_hir::Ty` representing each usage of `u32`. Each has its own `Span`s, etc.- `rustc_hir::Ty` doesn’t tell us that both are the same type | `fn foo(x: u32) → u32 { }` - One `ty::Ty` for all instances of `u32` throughout the program.- `ty::Ty` tells us that both usages of `u32` mean the same type. | +| `fn foo(x: &u32) -> &u32)`- Two `rustc_hir::Ty` again.- Lifetimes for the references show up in the `rustc_hir::Ty`s using a special marker, [`LifetimeName::Implicit`][implicit]. | `fn foo(x: &u32) -> &u32)`- A single `ty::Ty`.- The `ty::Ty` has the hidden lifetime param | + +[implicit]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.LifetimeName.html#variant.Implicit + +**Order** HIR is built directly from the AST, so it happens before any `ty::Ty` is produced. After +HIR is built, some basic type inference and type checking is done. During the type inference, we +figure out what the `ty::Ty` of everything is and we also check if the type of something is +ambiguous. The `ty::Ty` then, is used for type checking while making sure everything has the +expected type. The [`astconv` module][astconv], is where the code responsible for converting a +`rustc_hir::Ty` into a `ty::Ty` is located. This occurs during the type-checking phase, +but also in other parts of the compiler that want to ask questions like "what argument types does +this function expect"?. + +[astconv]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_typeck/astconv/index.html + +**How semantics drive the two instances of `Ty`** You can think of HIR as the perspective +of the type information that assumes the least. We assume two things are distinct until they are +proven to be the same thing. In other words, we know less about them, so we should assume less about +them. + +They are syntactically two strings: `"u32"` at line N column 20 and `"u32"` at line N column 35. We +don’t know that they are the same yet. So, in the HIR we treat them as if they are different. Later, +we determine that they semantically are the same type and that’s the `ty::Ty` we use. + +Consider another example: `fn foo(x: T) -> u32` and suppose that someone invokes `foo::(0)`. +This means that `T` and `u32` (in this invocation) actually turns out to be the same type, so we +would eventually end up with the same `ty::Ty` in the end, but we have distinct `rustc_hir::Ty`. +(This is a bit over-simplified, though, since during type checking, we would check the function +generically and would still have a `T` distinct from `u32`. Later, when doing code generation, +we would always be handling "monomorphized" (fully substituted) versions of each function, +and hence we would know what `T` represents (and specifically that it is `u32`). + +Here is one more example: + +```rust +mod a { + type X = u32; + pub fn foo(x: X) -> i32 { 22 } +} +mod b { + type X = i32; + pub fn foo(x: X) -> i32 { x } +} +``` + +Here the type `X` will vary depending on context, clearly. If you look at the `rustc_hir::Ty`, +you will get back that `X` is an alias in both cases (though it will be mapped via name resolution +to distinct aliases). But if you look at the `ty::Ty` signature, it will be either `fn(u32) -> u32` +or `fn(i32) -> i32` (with type aliases fully expanded). + +## `ty::Ty` implementation + +[`rustc::ty::Ty`][ty_ty] is actually a type alias to [`&TyS`][tys] (more about that later). `TyS` +(Type Structure) is where the main functionality is located. You can ignore `TyS` struct in general; +you will basically never access it explicitly. We always pass it by reference using the `Ty` alias. +The only exception is to define inherent methods on types. In particular, `TyS` has a [`kind`][kind] +field of type [`TyKind`][tykind], which represents the key type information. `TyKind` is a big enum +which represents different kinds of types (e.g. primitives, references, abstract data types, +generics, lifetimes, etc). `TyS` also has 2 more fields, `flags` and `outer_exclusive_binder`. They +are convenient hacks for efficiency and summarize information about the type that we may want to +know, but they don’t come into the picture as much here. Finally, `ty::TyS`s +are [interned](./memory.md), so that the `ty::Ty` can be a thin pointer-like +type. This allows us to do cheap comparisons for equality, along with the other +benefits of interning. + +[tys]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyS.html +[kind]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyS.html#structfield.kind +[tykind]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html + +## Allocating and working with types + +To allocate a new type, you can use the various `mk_` methods defined on the `tcx`. These have names +that correspond mostly to the various kinds of types. For example: + +```rust,ignore +let array_ty = tcx.mk_array(elem_ty, len * 2); +``` + +These methods all return a `Ty<'tcx>` – note that the lifetime you get back is the lifetime of the +arena that this `tcx` has access to. Types are always canonicalized and interned (so we never +allocate exactly the same type twice). + +> NB. Because types are interned, it is possible to compare them for equality efficiently using `==` +> – however, this is almost never what you want to do unless you happen to be hashing and looking +> for duplicates. This is because often in Rust there are multiple ways to represent the same type, +> particularly once inference is involved. If you are going to be testing for type equality, you +> probably need to start looking into the inference code to do it right. + +You can also find various common types in the `tcx` itself by accessing `tcx.types.bool`, +`tcx.types.char`, etc (see [`CommonTypes`] for more). + +[`CommonTypes`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/context/struct.CommonTypes.html + +## `ty::TyKind` Variants + +Note: `TyKind` is **NOT** the functional programming concept of *Kind*. + +Whenever working with a `Ty` in the compiler, it is common to match on the kind of type: + +```rust,ignore +fn foo(x: Ty<'tcx>) { + match x.kind { + ... + } +} +``` + +The `kind` field is of type `TyKind<'tcx>`, which is an enum defining all of the different kinds of +types in the compiler. + +> N.B. inspecting the `kind` field on types during type inference can be risky, as there may be +> inference variables and other things to consider, or sometimes types are not yet known and will +> become known later. + +There are a lot of related types, and we’ll cover them in time (e.g regions/lifetimes, +“substitutions”, etc). + +There are a bunch of variants on the `TyKind` enum, which you can see by looking at the rustdocs. +Here is a sampling: + +[**Algebraic Data Types (ADTs)**]() An [*algebraic Data Type*][wikiadt] is a `struct`, `enum` or +`union`. Under the hood, `struct`, `enum` and `union` are actually implemented the same way: they +are both [`ty::TyKind::Adt`][kindadt]. It’s basically a user defined type. We will talk more about +these later. + +[**Foreign**][kindforeign] Corresponds to `extern type T`. + +[**Str**][kindstr] Is the type str. When the user writes `&str`, `Str` is the how we represent the +`str` part of that type. + +[**Slice**][kindslice] Corresponds to `[T]`. + +[**Array**][kindarray] Corresponds to `[T; n]`. + +[**RawPtr**][kindrawptr] Corresponds to `*mut T` or `*const T` + +[**Ref**][kindref] `Ref` stands for safe references, `&'a mut T` or `&'a T`. `Ref` has some +associated parts, like `Ty<'tcx>` which is the type that the reference references, `Region<'tcx>` is +the lifetime or region of the reference and `Mutability` if the reference is mutable or not. + +[**Param**][kindparam] Represents a type parameter (e.g. the `T` in `Vec`). + +[**Error**][kinderr] Represents a type error somewhere so that we can print better diagnostics. We +will discuss this more later. + +[**And Many More**...][kindvars] + +[wikiadt]: https://en.wikipedia.org/wiki/Algebraic_data_type +[kindadt]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Adt +[kindforeign]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Foreign +[kindstr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Str +[kindslice]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Slice +[kindarray]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Array +[kindrawptr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.RawPtr +[kindref]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Ref +[kindparam]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Param +[kinderr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Error +[kindvars]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variants + +## Import conventions + +Although there is no hard and fast rule, the `ty` module tends to be used like so: + +```rust,ignore +use ty::{self, Ty, TyCtxt}; +``` + +In particular, since they are so common, the `Ty` and `TyCtxt` types are imported directly. Other +types are often referenced with an explicit `ty::` prefix (e.g. `ty::TraitRef<'tcx>`). But some +modules choose to import a larger or smaller set of names explicitly. + +## ADTs Representation + +Let's consider the example of a type like `MyStruct`, where `MyStruct` is defined like so: + +```rust,ignore +struct MyStruct { x: u32, y: T } +``` + +The type `MyStruct` would be an instance of `TyKind::Adt`: + +```rust,ignore +Adt(&'tcx AdtDef, SubstsRef<'tcx>) +// ------------ --------------- +// (1) (2) +// +// (1) represents the `MyStruct` part +// (2) represents the ``, or "substitutions" / generic arguments +``` + +There are two parts: + +- The [`AdtDef`][adtdef] references the struct/enum/union but without the values for its type + parameters. In our example, this is the `MyStruct` part *without* the argument `u32`. + - Note that in the HIR, structs, enums and unions are represented differently, but in `ty::Ty`, + they are all represented using `TyKind::Adt`. +- The [`SubstsRef`][substsref] is an interned list of values that are to be substituted for the + generic parameters. In our example of `MyStruct`, we would end up with a list like `[u32]`. + We’ll dig more into generics and substitutions in a little bit. + +[adtdef]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.AdtDef.html +[substsref]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/type.SubstsRef.html + +**`AdtDef` and `DefId`** + +For every type defined in the source code, there is a unique `DefId` (see [this +chapter](hir.md#identifiers-in-the-hir)). This includes ADTs and generics. In the `MyStruct` +definition we gave above, there are two `DefId`s: one for `MyStruct` and one for `T`. Notice that +the code above does not generate a new `DefId` for `u32` because it is not defined in that code (it +is only referenced). + +`AdtDef` is more or less a wrapper around `DefId` with lots of useful helper methods. There is +essentially a one-to-one relationship between `AdtDef` and `DefId`. You can get the `AdtDef` for a +`DefId` with the [`tcx.adt_def(def_id)` query][adtdefq]. The `AdtDef`s are all interned (as you can +see `'tcx` lifetime on it). + +[adtdefq]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyCtxt.html#method.adt_def + + +## Type errors + +There is a `TyKind::Error` that is produced when the user makes a type error. The idea is that +we would propagate this type and suppress other errors that come up due to it so as not to overwhelm +the user with cascading compiler error messages. + +There is an **important invariant** for `TyKind::Error`. You should **never** return the 'error +type' unless you **know** that an error has already been reported to the user. This is usually +because (a) you just reported it right there or (b) you are propagating an existing Error type (in +which case the error should've been reported when that error type was produced). + +It's important to maintain this invariant because the whole point of the `Error` type is to suppress +other errors -- i.e., we don't report them. If we were to produce an `Error` type without actually +emitting an error to the user, then this could cause later errors to be suppressed, and the +compilation might inadvertently succeed! + +Sometimes there is a third case. You believe that an error has been reported, but you believe it +would've been reported earlier in the compilation, not locally. In that case, you can invoke +[`delay_span_bug`] This will make a note that you expect compilation to yield an error -- if however +compilation should succeed, then it will trigger a compiler bug report. + +[`delay_span_bug`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/struct.Session.html#method.delay_span_bug + +## Question: Why not substitute “inside” the `AdtDef`? + +Recall that we represent a generic struct with `(AdtDef, substs)`. So why bother with this scheme? + +Well, the alternate way we could have choosen to represent types would be to always create a new, +fully-substituted form of the `AdtDef` where all the types are already substituted. This seems like +less of a hassle. However, the `(AdtDef, substs)` scheme has some advantages over this. + +First, `(AdtDef, substs)` scheme has an efficiency win: + +```rust,ignore +struct MyStruct { + ... 100s of fields ... +} + +// Want to do: MyStruct ==> MyStruct +``` + +in an example like this, we can subst from `MyStruct` to `MyStruct` (and so on) very cheaply, +by just replacing the one reference to `A` with `B`. But if we eagerly substituted all the fields, +that could be a lot more work because we might have to go through all of the fields in the `AdtDef` +and update all of their types. + +A bit more deeply, this corresponds to structs in Rust being [*nominal* types][nominal] — which +means that they are defined by their *name* (and that their contents are then indexed from the +definition of that name, and not carried along “within” the type itself). + +[nominal]: https://en.wikipedia.org/wiki/Nominal_type_system diff --git a/src/doc/rustc-guide/src/type-checking.md b/src/doc/rustc-dev-guide/src/type-checking.md similarity index 100% rename from src/doc/rustc-guide/src/type-checking.md rename to src/doc/rustc-dev-guide/src/type-checking.md diff --git a/src/doc/rustc-guide/src/type-inference.md b/src/doc/rustc-dev-guide/src/type-inference.md similarity index 97% rename from src/doc/rustc-guide/src/type-inference.md rename to src/doc/rustc-dev-guide/src/type-inference.md index d4734525f7..dca93dbdf3 100644 --- a/src/doc/rustc-guide/src/type-inference.md +++ b/src/doc/rustc-dev-guide/src/type-inference.md @@ -43,17 +43,12 @@ tcx.infer_ctxt().enter(|infcx| { }) ``` -Each inference context creates a short-lived type arena to store the -fresh types and things that it will create, as described in the -[chapter on the `ty` module][ty-ch]. This arena is created by the `enter` -function and disposed of after it returns. - -[ty-ch]: ty.html - Within the closure, `infcx` has the type `InferCtxt<'cx, 'tcx>` for some fresh `'cx`, while `'tcx` is the same as outside the inference context. (Again, see the [`ty` chapter][ty-ch] for more details on this setup.) +[ty-ch]: ty.html + The `tcx.infer_ctxt` method actually returns a builder, which means there are some kinds of configuration you can do before the `infcx` is created. See `InferCtxtBuilder` for more information. diff --git a/src/doc/rustc-guide/src/variance.md b/src/doc/rustc-dev-guide/src/variance.md similarity index 100% rename from src/doc/rustc-guide/src/variance.md rename to src/doc/rustc-dev-guide/src/variance.md diff --git a/src/doc/rustc-guide/src/walkthrough.md b/src/doc/rustc-dev-guide/src/walkthrough.md similarity index 100% rename from src/doc/rustc-guide/src/walkthrough.md rename to src/doc/rustc-dev-guide/src/walkthrough.md diff --git a/src/doc/rustc-guide/triagebot.toml b/src/doc/rustc-dev-guide/triagebot.toml similarity index 100% rename from src/doc/rustc-guide/triagebot.toml rename to src/doc/rustc-dev-guide/triagebot.toml diff --git a/src/doc/rustc-guide/README.md b/src/doc/rustc-guide/README.md deleted file mode 100644 index 12d46b4e52..0000000000 --- a/src/doc/rustc-guide/README.md +++ /dev/null @@ -1,85 +0,0 @@ -![Travis CI badge](https://api.travis-ci.com/rust-lang/rustc-guide.svg?branch=master) - - -This is a collaborative effort to build a guide that explains how rustc -works. The aim of the guide is to help new contributors get oriented -to rustc, as well as to help more experienced folks in figuring out -some new part of the compiler that they haven't worked on before. - -[You can read the latest version of the guide here.](https://rust-lang.github.io/rustc-guide/) - -You may also find the rustdocs [for the compiler itself][rustdocs] useful. - -[rustdocs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ - -### Contributing to the guide - -The guide is useful today, but it has a lot of work still go. - -If you'd like to help improve the guide, we'd love to have you! You can find -plenty of issues on the [issue -tracker](https://github.com/rust-lang/rustc-guide/issues). Just post a -comment on the issue you would like to work on to make sure that we don't -accidentally duplicate work. If you think something is missing, please open an -issue about it! - -**In general, if you don't know how the compiler works, that is not a -problem!** In that case, what we will do is to schedule a bit of time -for you to talk with someone who **does** know the code, or who wants -to pair with you and figure it out. Then you can work on writing up -what you learned. - -In general, when writing about a particular part of the compiler's code, we -recommend that you link to the relevant parts of the [rustc -rustdocs][rustdocs]. - -To help prevent accidentally introducing broken links, we use the -`mdbook-linkcheck`. If installed on your machine `mdbook` will automatically -invoke this link checker, otherwise it will emit a warning saying it couldn't -be found. - -```bash -> cargo install mdbook-linkcheck -``` - -You will need `mdbook` version `>= 0.2`. `linkcheck` will be run automatically -when you run `mdbook build`. - -## How to fix toolstate failures - -1. You will get a ping from the toolstate commit. e.g. https://github.com/rust-lang-nursery/rust-toolstate/commit/8ffa0e4c30ac9ba8546b7046e5c4ccc2b96ebdd4 - -2. The commit contains a link to the PR that caused the breakage. e.g. https://github.com/rust-lang/rust/pull/64321 - -3. If you go to that PR's thread, there is a post from bors with a link to the CI status: https://github.com/rust-lang/rust/pull/64321#issuecomment-529763807 - -4. Follow the check-azure link to get to the Azure website for that build: https://dev.azure.com/rust-lang/e71b0ddf-dd27-435a-873c-e30f86eea377/_build/results?buildId=7780 - -5. There will be approximately 1 billion different jobs for the build. They are for different configurations and platforms. The rustc-guide build only runs on the Linux x86_64-gnu-tools job. So click on that job in the list, which is about 60% down in the list. - -6. Click the Run build step in the job to get the console log for the step. - -7. Click on the log and Ctrl-f to get a search box in the log - -8. Search for rustc-guide. This gets you to the place where the links are checked. It is usually ~11K lines into the log - -9. Look at the links in the log near that point in the log - -10. Fix those links in the rustc-guide (by making a PR in the rustc-guide repo) - -11. Make a PR on the rust-lang/rust repo to update the rustc-guide git submodule in src/docs/rustc-guide. -To make a PR, the following steps are useful. - -```bash -# Assuming you already cloned the rust-lang/rust repo and you're in the correct directory -git submodule update --remote src/doc/rustc-guide -git add -u -git commit -m "Update rustc-guide" -# Note that you can use -i, which is short for --incremental, in the following command -./x.py test --incremental --stage 1 src/doc/rustc-guide # This is optional and should succeed anyway -# Open a PR in rust-lang/rust -``` - -12. Wait for PR to merge - -Voila! diff --git a/src/doc/rustc-guide/book.toml b/src/doc/rustc-guide/book.toml deleted file mode 100644 index 3a5b1fd6dc..0000000000 --- a/src/doc/rustc-guide/book.toml +++ /dev/null @@ -1,20 +0,0 @@ -[book] -title = "Guide to Rustc Development" -author = "Rustc developers" -description = "A guide to developing rustc" - -[build] -create-missing = false - -[output.html] -git-repository-url = "https://github.com/rust-lang/rustc-guide" - -[output.html.fold] -enable = true -level = 1 - -[output.linkcheck] -follow-web-links = true -exclude = [ "crates\\.io", "gcc\\.godbolt\\.org", "youtube\\.com", "youtu\\.be", "dl\\.acm\\.org", "cs\\.bgu\\.ac\\.il" ] -cache-timeout = 172800 -warning-policy = "error" diff --git a/src/doc/rustc-guide/ci/install.sh b/src/doc/rustc-guide/ci/install.sh deleted file mode 100755 index 5cb2f41fca..0000000000 --- a/src/doc/rustc-guide/ci/install.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash - -set -ex - -function cargo_install() { - local name=$1 - local version=$2 - - if command -v $name >/dev/null 2>&1; then - local installed_version=`$name --version | sed -E 's/[a-zA-Z_-]+ v?//g'` - if [ "$installed_version" == "$version" ]; then - echo "$name $version is already installed at $(command -v $name)" - else - echo "Forcing install $name $version" - cargo install $name --version $version --force - fi - else - echo "Installing $name $version" - cargo install $name --version $version - fi -} - -cargo_install mdbook 0.3.4 -cargo_install mdbook-linkcheck 0.5.0 diff --git a/src/doc/rustc-guide/src/appendix/compiler-lecture.md b/src/doc/rustc-guide/src/appendix/compiler-lecture.md deleted file mode 100644 index 3912bab767..0000000000 --- a/src/doc/rustc-guide/src/appendix/compiler-lecture.md +++ /dev/null @@ -1,51 +0,0 @@ -# Compiler Lecture Series - -These are videos where various experts explain different parts of the compiler: - -- Tom Tromey discusses debugging support in rustc - - Video: https://www.youtube.com/watch?v=elBxMRSNYr4 -- How Salsa Works (2019.01) - - Video: https://www.youtube.com/watch?v=_muY4HjSqVw -- Salsa In More Depth (2019.01) - - Video: https://www.youtube.com/watch?v=i_IhACacPRY -- RLS 2.0, Salsa, and Name Resolution - - Video: https://www.youtube.com/watch?v=Xr-rBqLr-G4 -- Cranelift - - Video: https://www.youtube.com/watch?v=9OIA7DTFQWU -- Rust analyzer guide - - Video: https://www.youtube.com/watch?v=ANKBNiSWyfc -- Rust analyzer syntax trees - - Video: https://www.youtube.com/watch?v=DGAuLWdCCAI -- rust-analyzer type-checker overview by flodiebold - - Video: https://www.youtube.com/watch?v=Lmp3P9WNL8o -- oli-obk on miri and constant evaluation - - Video: https://www.youtube.com/watch?v=5Pm2C1YXrvM -- Polonius-rustc walkthrough - - Video: https://www.youtube.com/watch?v=i5KdU0ieb_A -- rustc-chalk integration overview - - Video: https://www.youtube.com/watch?v=MBWtbDifPeU -- Coherence in Chalk by Sunjay Varma - Bay Area Rust Meetup - - assigned to @juanbono - - Video: https://www.youtube.com/watch?v=rZqS4bLPL24 -- How the chalk-engine crate works - - Video: https://www.youtube.com/watch?v=Ny2928cGDoM -- How the chalk-engine crate works 2 - - Video: https://www.youtube.com/watch?v=hmV66tB79LM -- RFC #2229 Disjoint Field Capture plan - - Video: https://www.youtube.com/watch?v=UTXOptVMuIc -- closures and upvar capture - - Video: https://www.youtube.com/watch?v=fMopdkn5-Xw -- blitzerr closure upvar tys - - Video: https://www.youtube.com/watch?v=pLmVhSB-z4s -- Convert Closure Upvar Representation to Tuples with blitzerr - - Video: https://www.youtube.com/watch?v=2QCuNtISoYc -- async-await implementation plans - - Video: https://www.youtube.com/watch?v=xe2_whJWBC0 -- async-await region inferencer - - Video: https://www.youtube.com/watch?v=hlOxfkUDLPQ -- Universes and Lifetimes - - Video: https://www.youtube.com/watch?v=iV1Z0xYXkck -- Representing types in rustc - - Video: https://www.youtube.com/watch?v=c01TsOsr3-c -- Polonius WG: Initialization and move tracking - - Video: https://www.youtube.com/watch?v=ilv9V-328HI diff --git a/src/doc/rustc-guide/src/appendix/glossary.md b/src/doc/rustc-guide/src/appendix/glossary.md deleted file mode 100644 index a773e35215..0000000000 --- a/src/doc/rustc-guide/src/appendix/glossary.md +++ /dev/null @@ -1,87 +0,0 @@ -# Appendix C: Glossary - -The compiler uses a number of...idiosyncratic abbreviations and things. This -glossary attempts to list them and give you a few pointers for understanding -them better. - -Term | Meaning -------------------------|-------- -AST | the abstract syntax tree produced by the syntax crate; reflects user syntax very closely. -binder | a "binder" is a place where a variable or type is declared; for example, the `` is a binder for the generic type parameter `T` in `fn foo(..)`, and \|`a`\|` ...` is a binder for the parameter `a`. See [the background chapter for more](./background.html#free-vs-bound) -bound variable | a "bound variable" is one that is declared within an expression/term. For example, the variable `a` is bound within the closure expression \|`a`\|` a * 2`. See [the background chapter for more](./background.html#free-vs-bound) -codegen | the code to translate MIR into LLVM IR. -codegen unit | when we produce LLVM IR, we group the Rust code into a number of codegen units (sometimes abbreviated as CGUs). Each of these units is processed by LLVM independently from one another, enabling parallelism. They are also the unit of incremental re-use. -completeness | completeness is a technical term in type theory. Completeness means that every type-safe program also type-checks. Having both soundness and completeness is very hard, and usually soundness is more important. (see "soundness"). -control-flow graph | a representation of the control-flow of a program; see [the background chapter for more](./background.html#cfg) -CTFE | Compile-Time Function Evaluation. This is the ability of the compiler to evaluate `const fn`s at compile time. This is part of the compiler's constant evaluation system. ([see more](../const-eval.html)) -cx | we tend to use "cx" as an abbreviation for context. See also `tcx`, `infcx`, etc. -DAG | a directed acyclic graph is used during compilation to keep track of dependencies between queries. ([see more](../queries/incremental-compilation.html)) -data-flow analysis | a static analysis that figures out what properties are true at each point in the control-flow of a program; see [the background chapter for more](./background.html#dataflow) -DefId | an index identifying a definition (see `librustc/hir/def_id.rs`). Uniquely identifies a `DefPath`. -Double pointer | a pointer with additional metadata. See "fat pointer" for more. -drop glue | (internal) compiler-generated instructions that handle calling the destructors (`Drop`) for data types. -DST | Dynamically-Sized Type. A type for which the compiler cannot statically know the size in memory (e.g. `str` or `[u8]`). Such types don't implement `Sized` and cannot be allocated on the stack. They can only occur as the last field in a struct. They can only be used behind a pointer (e.g. `&str` or `&[u8]`). -early-bound lifetime | a lifetime region that is substituted at its definition site. Bound in an item's `Generics` and substituted using a `Substs`. Contrast with **late-bound lifetime**. ([see more](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.RegionKind.html#bound-regions)) -empty type | see "uninhabited type". -Fat pointer | a two word value carrying the address of some value, along with some further information necessary to put the value to use. Rust includes two kinds of "fat pointers": references to slices, and trait objects. A reference to a slice carries the starting address of the slice and its length. A trait object carries a value's address and a pointer to the trait's implementation appropriate to that value. "Fat pointers" are also known as "wide pointers", and "double pointers". -free variable | a "free variable" is one that is not bound within an expression or term; see [the background chapter for more](./background.html#free-vs-bound) -generics | the set of generic type parameters defined on a type or item -HIR | the High-level IR, created by lowering and desugaring the AST ([see more](../hir.html)) -HirId | identifies a particular node in the HIR by combining a def-id with an "intra-definition offset". -HIR Map | The HIR map, accessible via tcx.hir, allows you to quickly navigate the HIR and convert between various forms of identifiers. -ICE | internal compiler error. When the compiler crashes. -ICH | incremental compilation hash. ICHs are used as fingerprints for things such as HIR and crate metadata, to check if changes have been made. This is useful in incremental compilation to see if part of a crate has changed and should be recompiled. -inference variable | when doing type or region inference, an "inference variable" is a kind of special type/region that represents what you are trying to infer. Think of X in algebra. For example, if we are trying to infer the type of a variable in a program, we create an inference variable to represent that unknown type. -infcx | the inference context (see `librustc/infer`) -intern | interning refers to storing certain frequently-used constant data, such as strings, and then referring to the data by an identifier (e.g. a `Symbol`) rather than the data itself, to reduce memory usage. -IR | Intermediate Representation. A general term in compilers. During compilation, the code is transformed from raw source (ASCII text) to various IRs. In Rust, these are primarily HIR, MIR, and LLVM IR. Each IR is well-suited for some set of computations. For example, MIR is well-suited for the borrow checker, and LLVM IR is well-suited for codegen because LLVM accepts it. -IRLO | `IRLO` or `irlo` is sometimes used as an abbreviation for [internals.rust-lang.org](https://internals.rust-lang.org). -item | a kind of "definition" in the language, such as a static, const, use statement, module, struct, etc. Concretely, this corresponds to the `Item` type. -lang item | items that represent concepts intrinsic to the language itself, such as special built-in traits like `Sync` and `Send`; or traits representing operations such as `Add`; or functions that are called by the compiler. ([see more](https://doc.rust-lang.org/1.9.0/book/lang-items.html)) -late-bound lifetime | a lifetime region that is substituted at its call site. Bound in a HRTB and substituted by specific functions in the compiler, such as `liberate_late_bound_regions`. Contrast with **early-bound lifetime**. ([see more](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.RegionKind.html#bound-regions)) -local crate | the crate currently being compiled. -LTO | Link-Time Optimizations. A set of optimizations offered by LLVM that occur just before the final binary is linked. These include optimizations like removing functions that are never used in the final program, for example. _ThinLTO_ is a variant of LTO that aims to be a bit more scalable and efficient, but possibly sacrifices some optimizations. You may also read issues in the Rust repo about "FatLTO", which is the loving nickname given to non-Thin LTO. LLVM documentation: [here][lto] and [here][thinlto] -[LLVM] | (actually not an acronym :P) an open-source compiler backend. It accepts LLVM IR and outputs native binaries. Various languages (e.g. Rust) can then implement a compiler front-end that output LLVM IR and use LLVM to compile to all the platforms LLVM supports. -memoize | memoization is the process of storing the results of (pure) computations (such as pure function calls) to avoid having to repeat them in the future. This is typically a trade-off between execution speed and memory usage. -MIR | the Mid-level IR that is created after type-checking for use by borrowck and codegen ([see more](../mir/index.html)) -miri | an interpreter for MIR used for constant evaluation ([see more](../miri.html)) -monomorphize | Monomorphization is the process of taking generic implementations of types and functions and instantiating them with concrete types. For example, in the code we might have `Vec`, but in the final executable, we will have a copy of the `Vec` code for every concrete type used in the program (e.g. a copy for `Vec`, a copy for `Vec`, etc). -normalize | a general term for converting to a more canonical form, but in the case of rustc typically refers to [associated type normalization](../traits/associated-types.html#normalize) -newtype | a "newtype" is a wrapper around some other type (e.g., `struct Foo(T)` is a "newtype" for `T`). This is commonly used in Rust to give a stronger type for indices. -NLL | [non-lexical lifetimes](../borrow_check/region_inference.html), an extension to Rust's borrowing system to make it be based on the control-flow graph. -node-id or NodeId | an index identifying a particular node in the AST or HIR; gradually being phased out and replaced with `HirId`. -obligation | something that must be proven by the trait system ([see more](../traits/resolution.html)) -point | used in the NLL analysis to refer to some particular location in the MIR; typically used to refer to a node in the control-flow graph. -projection | a general term for a "relative path", e.g. `x.f` is a "field projection", and `T::Item` is an ["associated type projection"](../traits/goals-and-clauses.html#trait-ref) -promoted constants | constants extracted from a function and lifted to static scope; see [this section](../mir/index.html#promoted) for more details. -provider | the function that executes a query ([see more](../query.html)) -quantified | in math or logic, existential and universal quantification are used to ask questions like "is there any type T for which is true?" or "is this true for all types T?"; see [the background chapter for more](./background.html#quantified) -query | perhaps some sub-computation during compilation ([see more](../query.html)) -region | another term for "lifetime" often used in the literature and in the borrow checker. -rib | a data structure in the name resolver that keeps track of a single scope for names. ([see more](../name-resolution.html)) -sess | the compiler session, which stores global data used throughout compilation -side tables | because the AST and HIR are immutable once created, we often carry extra information about them in the form of hashtables, indexed by the id of a particular node. -sigil | like a keyword but composed entirely of non-alphanumeric tokens. For example, `&` is a sigil for references. -placeholder | **NOTE: skolemization is deprecated by placeholder** a way of handling subtyping around "for-all" types (e.g., `for<'a> fn(&'a u32)`) as well as solving higher-ranked trait bounds (e.g., `for<'a> T: Trait<'a>`). See [the chapter on placeholder and universes](../borrow_check/region_inference/placeholders_and_universes.md) for more details. -soundness | soundness is a technical term in type theory. Roughly, if a type system is sound, then if a program type-checks, it is type-safe; i.e. I can never (in safe rust) force a value into a variable of the wrong type. (see "completeness"). -span | a location in the user's source code, used for error reporting primarily. These are like a file-name/line-number/column tuple on steroids: they carry a start/end point, and also track macro expansions and compiler desugaring. All while being packed into a few bytes (really, it's an index into a table). See the Span datatype for more. -substs | the substitutions for a given generic type or item (e.g. the `i32`, `u32` in `HashMap`) -tcx | the "typing context", main data structure of the compiler ([see more](../ty.html)) -'tcx | the lifetime of the allocation arena ([see more](../ty.html)) -trait reference | the name of a trait along with a suitable set of input type/lifetimes ([see more](../traits/goals-and-clauses.html#trait-ref)) -token | the smallest unit of parsing. Tokens are produced after lexing ([see more](../the-parser.html)). -[TLS] | Thread-Local Storage. Variables may be defined so that each thread has its own copy (rather than all threads sharing the variable). This has some interactions with LLVM. Not all platforms support TLS. -trans | the code to translate MIR into LLVM IR. Renamed to codegen. -trait reference | a trait and values for its type parameters ([see more](../ty.html)). -ty | the internal representation of a type ([see more](../ty.html)). -UFCS | Universal Function Call Syntax. An unambiguous syntax for calling a method ([see more](../type-checking.html)). -uninhabited type | a type which has _no_ values. This is not the same as a ZST, which has exactly 1 value. An example of an uninhabited type is `enum Foo {}`, which has no variants, and so, can never be created. The compiler can treat code that deals with uninhabited types as dead code, since there is no such value to be manipulated. `!` (the never type) is an uninhabited type. Uninhabited types are also called "empty types". -upvar | a variable captured by a closure from outside the closure. -variance | variance determines how changes to a generic type/lifetime parameter affect subtyping; for example, if `T` is a subtype of `U`, then `Vec` is a subtype `Vec` because `Vec` is *covariant* in its generic parameter. See [the background chapter](./background.html#variance) for a more general explanation. See the [variance chapter](../variance.html) for an explanation of how type checking handles variance. -Wide pointer | a pointer with additional metadata. See "fat pointer" for more. -ZST | Zero-Sized Type. A type whose values have size 0 bytes. Since `2^0 = 1`, such types can have exactly one value. For example, `()` (unit) is a ZST. `struct Foo;` is also a ZST. The compiler can do some nice optimizations around ZSTs. - -[LLVM]: https://llvm.org/ -[lto]: https://llvm.org/docs/LinkTimeOptimization.html -[thinlto]: https://clang.llvm.org/docs/ThinLTO.html -[TLS]: https://llvm.org/docs/LangRef.html#thread-local-storage-models diff --git a/src/doc/rustc-guide/src/sanitizers.md b/src/doc/rustc-guide/src/sanitizers.md deleted file mode 100644 index 6205433e59..0000000000 --- a/src/doc/rustc-guide/src/sanitizers.md +++ /dev/null @@ -1,68 +0,0 @@ -# Sanitizers Support - -The rustc compiler contains basic support for following sanitizers: - -* [AddressSanitizer][clang-asan] a faster memory error detector. Can - detect out-of-bounds access to heap, stack, and globals, use after free, use - after return, double free, invalid free, memory leaks. -* [LeakSanitizer][clang-lsan] a run-time memory leak detector. -* [MemorySanitizer][clang-msan] a detector of uninitialized reads. -* [ThreadSanitizer][clang-tsan] a fast data race detector. - -## How to use the sanitizers? - -To enable a sanitizer compile with `-Zsanitizer=...` option, where value is one -of `address`, `leak`, `memory` or `thread`. For more details how to use -sanitizers please refer to [the unstable book](https://doc.rust-lang.org/unstable-book/). - -## How are sanitizers implemented in rustc? - -The implementation of sanitizers relies entirely on LLVM. It consists of -compile time instrumentation passes and runtime libraries. The role rustc plays -in the implementation is limited to the execution of the following steps: - -1. The sanitizer runtime libraries are part of the [compiler-rt] project, and - [will be built as an LLVM subproject][sanitizer-build] when enabled in - `config.toml`: - - ```toml - [build] - sanitizers = true - ``` - - The runtimes are [placed into target libdir][sanitizer-copy]. - -2. During LLVM code generation, the functions intended for instrumentation are - [marked][sanitizer-attribute] with `SanitizeAddress`, `SanitizeMemory`, or - `SanitizeThread` attribute. Currently those attributes are applied in - indiscriminate manner. but in principle they could be used to perform - instrumentation selectively. - -3. The LLVM IR generated by rustc is instrumented by [dedicated LLVM - passes][sanitizer-pass], different for each sanitizer. Instrumentation - passes are invoked after optimization passes. - -4. When producing an executable, the sanitizer specific runtime library is - [linked in][sanitizer-link]. The libraries are searched for in target libdir - relative to default system root, so that this process is not affected - by sysroot overrides used for example by cargo `-Zbuild-std` functionality. - -[compiler-rt]: https://github.com/llvm/llvm-project/tree/master/compiler-rt -[sanitizer-build]: https://github.com/rust-lang/rust/blob/87c3eedffba64830b67e54e75dd479f9fd83cc7d/src/bootstrap/native.rs#L220-L225 -[sanitizer-copy]: https://github.com/rust-lang/rust/blob/87c3eedffba64830b67e54e75dd479f9fd83cc7d/src/bootstrap/compile.rs#L269-L321 -[sanitizer-attribute]: https://github.com/rust-lang/rust/blob/1.38.0/src/librustc_codegen_llvm/declare.rs#L53-L66 -[sanitizer-pass]: https://github.com/rust-lang/rust/blob/1.38.0/src/librustc_codegen_ssa/back/write.rs#L406-L420 -[sanitizer-link]: https://github.com/rust-lang/rust/blob/87c3eedffba64830b67e54e75dd479f9fd83cc7d/src/librustc_codegen_ssa/back/link.rs#L729-L770 - -## Additional Information - -* [Sanitizers project page](https://github.com/google/sanitizers/wiki/) -* [AddressSanitizer in Clang][clang-asan] -* [LeakSanitizer in Clang][clang-lsan] -* [MemorySanitizer in Clang][clang-msan] -* [ThreadSanitizer in Clang][clang-tsan] - -[clang-asan]: https://clang.llvm.org/docs/AddressSanitizer.html -[clang-lsan]: https://clang.llvm.org/docs/LeakSanitizer.html -[clang-msan]: https://clang.llvm.org/docs/MemorySanitizer.html -[clang-tsan]: https://clang.llvm.org/docs/ThreadSanitizer.html diff --git a/src/doc/rustc-guide/src/traits/lowering-module.md b/src/doc/rustc-guide/src/traits/lowering-module.md deleted file mode 100644 index 3f1515ef8a..0000000000 --- a/src/doc/rustc-guide/src/traits/lowering-module.md +++ /dev/null @@ -1,65 +0,0 @@ -# The lowering module in rustc - -The program clauses described in the -[lowering rules](./lowering-rules.html) section are actually -created in the [`rustc_traits::lowering`][lowering] module. - -[lowering]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_traits/lowering/ - -## The `program_clauses_for` query - -The main entry point is the `program_clauses_for` [query], which – -given a def-id – produces a set of Chalk program clauses. These -queries are tested using a -[dedicated unit-testing mechanism, described below](#unit-tests). The -query is invoked on a `DefId` that identifies something like a trait, -an impl, or an associated item definition. It then produces and -returns a vector of program clauses. - -[query]: ../query.html - - - -## Unit tests - -Unit tests are located in [`src/test/ui/chalkify`][chalkify]. A good -example test is [the `lower_impl` test][lower_impl]. At the time of -this writing, it looked like this: - -```rust,ignore -#![feature(rustc_attrs)] - -trait Foo { } - -#[rustc_dump_program_clauses] //~ ERROR program clause dump -impl Foo for T where T: Iterator { } - -fn main() { - println!("hello"); -} -``` - -The `#[rustc_dump_program_clauses]` annotation can be attached to -anything with a def-id. (It requires the `rustc_attrs` feature.) The -compiler will then invoke the `program_clauses_for` query on that -item, and emit compiler errors that dump the clauses produced. These -errors just exist for unit-testing, as we can then leverage the -standard [ui test] mechanisms to check them. In this case, there is a -`//~ ERROR program clause dump` annotation which is always the same for -`#[rustc_dump_program_clauses]`, but [the stderr file] contains -the full details: - -```text -error: program clause dump - --> $DIR/lower_impl.rs:5:1 - | -LL | #[rustc_dump_program_clauses] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: forall { Implemented(T: Foo) :- ProjectionEq(::Item == i32), TypeOutlives(T: 'static), Implemented(T: std::iter::Iterator), Implemented(T: std::marker::Sized). } -``` - -[chalkify]: https://github.com/rust-lang/rust/tree/master/src/test/ui/chalkify -[lower_impl]: https://github.com/rust-lang/rust/tree/master/src/test/ui/chalkify/lower_impl.rs -[the stderr file]: https://github.com/rust-lang/rust/tree/master/src/test/ui/chalkify/lower_impl.stderr -[ui test]: ../tests/adding.html#guide-to-the-ui-tests diff --git a/src/doc/rustc-guide/src/ty.md b/src/doc/rustc-guide/src/ty.md deleted file mode 100644 index b665dadf17..0000000000 --- a/src/doc/rustc-guide/src/ty.md +++ /dev/null @@ -1,636 +0,0 @@ ---- -tags: rustc, ty ---- - -# The `ty` module: representing types - -The `ty` module defines how the Rust compiler represents types internally. It also defines the -*typing context* (`tcx` or `TyCtxt`), which is the central data structure in the compiler. - -## `ty::Ty` - -When we talk about how rustc represents types, we usually refer to a type called `Ty` . There are -quite a few modules and types for `Ty` in the compiler ([Ty documentation][ty]). - -[ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/index.html - -The specific `Ty` we are referring to is [`rustc::ty::Ty`][ty_ty] (and not -[`rustc_hir::Ty`][hir_ty]). The distinction is important, so we will discuss it first before going -into the details of `ty::Ty`. - -[ty_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/type.Ty.html -[hir_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/struct.Ty.html - -## `rustc_hir::Ty` vs `ty::Ty` - -The HIR in rustc can be thought of as the high-level intermediate representation. It is more or less -the AST (see [this chapter](hir.md)) as it represents the -syntax that the user wrote, and is obtained after parsing and some *desugaring*. It has a -representation of types, but in reality it reflects more of what the user wrote, that is, what they -wrote so as to represent that type. - -In contrast, `ty::Ty` represents the semantics of a type, that is, the *meaning* of what the user -wrote. For example, `rustc_hir::Ty` would record the fact that a user used the name `u32` twice -in their program, but the `ty::Ty` would record the fact that both usages refer to the same type. - -**Example: `fn foo(x: u32) → u32 { }`** In this function we see that `u32` appears twice. We know -that that is the same type, i.e. the function takes an argument and returns an argument of the same -type, but from the point of view of the HIR there would be two distinct type instances because these -are occurring in two different places in the program. That is, they have two -different [`Span`s][span] (locations). - -[span]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html - -**Example: `fn foo(x: &u32) -> &u32)`** In addition, HIR might have information left out. This type -`&u32` is incomplete, since in the full rust type there is actually a lifetime, but we didn’t need -to write those lifetimes. There are also some elision rules that insert information. The result may -look like `fn foo<'a>(x: &'a u32) -> &'a u32)`. - -In the HIR level, these things are not spelled out and you can say the picture is rather incomplete. -However, at the `ty::Ty` level, these details are added and it is complete. Moreover, we will have -exactly one `ty::Ty` for a given type, like `u32`, and that `ty::Ty` is used for all `u32`s in the -whole program, not a specific usage, unlike `rustc_hir::Ty`. - -Here is a summary: - -| [`rustc_hir::Ty`][hir_ty] | [`ty::Ty`][ty_ty] | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Describe the *syntax* of a type: what the user wrote (with some desugaring). | Describe the *semantics* of a type: the meaning of what the user wrote. | -| Each `rustc_hir::Ty` has its own spans corresponding to the appropriate place in the program. | Doesn’t correspond to a single place in the user’s program. | -| `rustc_hir::Ty` has generics and lifetimes; however, some of those lifetimes are special markers like [`LifetimeName::Implicit`][implicit]. | `ty::Ty` has the full type, including generics and lifetimes, even if the user left them out | -| `fn foo(x: u32) → u32 { }` - Two `rustc_hir::Ty` representing each usage of `u32`. Each has its own `Span`s, etc.- `rustc_hir::Ty` doesn’t tell us that both are the same type | `fn foo(x: u32) → u32 { }` - One `ty::Ty` for all instances of `u32` throughout the program.- `ty::Ty` tells us that both usages of `u32` mean the same type. | -| `fn foo(x: &u32) -> &u32)`- Two `rustc_hir::Ty` again.- Lifetimes for the references show up in the `rustc_hir::Ty`s using a special marker, [`LifetimeName::Implicit`][implicit]. | `fn foo(x: &u32) -> &u32)`- A single `ty::Ty`.- The `ty::Ty` has the hidden lifetime param | - -[implicit]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.LifetimeName.html#variant.Implicit - -**Order** HIR is built directly from the AST, so it happens before any `ty::Ty` is produced. After -HIR is built, some basic type inference and type checking is done. During the type inference, we -figure out what the `ty::Ty` of everything is and we also check if the type of something is -ambiguous. The `ty::Ty` then, is used for type checking while making sure everything has the -expected type. The [`astconv` module][astconv], is where the code responsible for converting a -`rustc_hir::Ty` into a `ty::Ty` is located. This occurs during the type-checking phase, -but also in other parts of the compiler that want to ask questions like "what argument types does -this function expect"?. - -[astconv]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_typeck/astconv/index.html - -**How semantics drive the two instances of `Ty`** You can think of HIR as the perspective -of the type information that assumes the least. We assume two things are distinct until they are -proven to be the same thing. In other words, we know less about them, so we should assume less about -them. - -They are syntactically two strings: `"u32"` at line N column 20 and `"u32"` at line N column 35. We -don’t know that they are the same yet. So, in the HIR we treat them as if they are different. Later, -we determine that they semantically are the same type and that’s the `ty::Ty` we use. - -Consider another example: `fn foo(x: T) -> u32` and suppose that someone invokes `foo::(0)`. -This means that `T` and `u32` (in this invocation) actually turns out to be the same type, so we -would eventually end up with the same `ty::Ty` in the end, but we have distinct `rustc_hir::Ty`. -(This is a bit over-simplified, though, since during type checking, we would check the function -generically and would still have a `T` distinct from `u32`. Later, when doing code generation, -we would always be handling "monomorphized" (fully substituted) versions of each function, -and hence we would know what `T` represents (and specifically that it is `u32`). - -Here is one more example: - -```rust -mod a { - type X = u32; - pub fn foo(x: X) -> i32 { 22 } -} -mod b { - type X = i32; - pub fn foo(x: X) -> i32 { x } -} -``` - -Here the type `X` will vary depending on context, clearly. If you look at the `rustc_hir::Ty`, -you will get back that `X` is an alias in both cases (though it will be mapped via name resolution -to distinct aliases). But if you look at the `ty::Ty` signature, it will be either `fn(u32) -> u32` -or `fn(i32) -> i32` (with type aliases fully expanded). - -## `ty::Ty` implementation - -[`rustc::ty::Ty`][ty_ty] is actually a type alias to [`&TyS`][tys] (more about that later). `TyS` -(Type Structure) is where the main functionality is located. You can ignore `TyS` struct in general; -you will basically never access it explicitly. We always pass it by reference using the `Ty` alias. -The only exception is to define inherent methods on types. In particular, `TyS` has a [`kind`][kind] -field of type [`TyKind`][tykind], which represents the key type information. `TyKind` is a big enum -which represents different kinds of types (e.g. primitives, references, abstract data types, -generics, lifetimes, etc). `TyS` also has 2 more fields, `flags` and `outer_exclusive_binder`. They -are convenient hacks for efficiency and summarize information about the type that we may want to -know, but they don’t come into the picture as much here. - -[tys]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyS.html -[kind]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyS.html#structfield.kind -[tykind]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html - -Note: `TyKind` is **NOT** the functional programming concept of *Kind*. - -Whenever working with a `Ty` in the compiler, it is common to match on the kind of type: - -```rust,ignore -fn foo(x: Ty<'tcx>) { - match x.kind { - ... - } -} -``` - -The `kind` field is of type `TyKind<'tcx>`, which is an enum defining all of the different kinds of -types in the compiler. - -> N.B. inspecting the `kind` field on types during type inference can be risky, as there may be -> inference variables and other things to consider, or sometimes types are not yet known and will -> become known later. - -There are a lot of related types, and we’ll cover them in time (e.g regions/lifetimes, -“substitutions”, etc). - -## `ty::TyKind` Variants - -There are a bunch of variants on the `TyKind` enum, which you can see by looking at the rustdocs. -Here is a sampling: - -[**Algebraic Data Types (ADTs)**]() An [*algebraic Data Type*][wikiadt] is a `struct`, `enum` or -`union`. Under the hood, `struct`, `enum` and `union` are actually implemented the same way: they -are both [`ty::TyKind::Adt`][kindadt]. It’s basically a user defined type. We will talk more about -these later. - -[**Foreign**][kindforeign] Corresponds to `extern type T`. - -[**Str**][kindstr] Is the type str. When the user writes `&str`, `Str` is the how we represent the -`str` part of that type. - -[**Slice**][kindslice] Corresponds to `[T]`. - -[**Array**][kindarray] Corresponds to `[T; n]`. - -[**RawPtr**][kindrawptr] Corresponds to `*mut T` or `*const T` - -[**Ref**][kindref] `Ref` stands for safe references, `&'a mut T` or `&'a T`. `Ref` has some -associated parts, like `Ty<'tcx>` which is the type that the reference references, `Region<'tcx>` is -the lifetime or region of the reference and `Mutability` if the reference is mutable or not. - -[**Param**][kindparam] Represents a type parameter (e.g. the `T` in `Vec`). - -[**Error**][kinderr] Represents a type error somewhere so that we can print better diagnostics. We -will discuss this more later. - -[**And Many More**...][kindvars] - -[wikiadt]: https://en.wikipedia.org/wiki/Algebraic_data_type -[kindadt]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Adt -[kindforeign]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Foreign -[kindstr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Str -[kindslice]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Slice -[kindarray]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Array -[kindrawptr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.RawPtr -[kindref]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Ref -[kindparam]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Param -[kinderr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variant.Error -[kindvars]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.TyKind.html#variants - -## Interning - -We create a LOT of types during compilation. For performance reasons, we allocate them from a global -memory pool, they are each allocated once from a long-lived *arena*. This is called _arena -allocation_. This system reduces allocations/deallocations of memory. It also allows for easy -comparison of types for equality: we implemented [`PartialEq for TyS`][peqimpl], so we can just -compare pointers. The [`CtxtInterners`] type contains a bunch of maps of interned types and the -arena itself. - -[peqimpl]: https://github.com/rust-lang/rust/blob/3ee936378662bd2e74be951d6a7011a95a6bd84d/src/librustc/ty/mod.rs#L528-L534 -[`CtxtInterners`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.CtxtInterners.html#structfield.arena - -Each time we want to construct a type, the compiler doesn’t naively allocate from the buffer. -Instead, we check if that type was already constructed. If it was, we just get the same pointer we -had before, otherwise we make a fresh pointer. With this schema if we want to know if two types are -the same, all we need to do is compare the pointers which is efficient. `TyS` which represents types -is carefully setup so you never construct them on the stack. You always allocate them from this -arena and you always intern them so they are unique. - -At the beginning of the compilation we make a buffer and each time we need to allocate a type we use -some of this memory buffer. If we run out of space we get another one. The lifetime of that buffer -is `'tcx`. Our types are tied to that lifetime, so when compilation finishes all the memory related -to that buffer is freed and our `'tcx` references would be invalid. - - -## The tcx and how it uses lifetimes - -The `tcx` ("typing context") is the central data structure in the compiler. It is the context that -you use to perform all manner of queries. The struct `TyCtxt` defines a reference to this shared -context: - -```rust,ignore -tcx: TyCtxt<'tcx> -// ---- -// | -// arena lifetime -``` - -As you can see, the `TyCtxt` type takes a lifetime parameter. When you see a reference with a -lifetime like `'tcx`, you know that it refers to arena-allocated data (or data that lives as long as -the arenas, anyhow). - -## Allocating and working with types - -To allocate a new type, you can use the various `mk_` methods defined on the `tcx`. These have names -that correspond mostly to the various kinds of types. For example: - -```rust,ignore -let array_ty = tcx.mk_array(elem_ty, len * 2); -``` - -These methods all return a `Ty<'tcx>` – note that the lifetime you get back is the lifetime of the -arena that this `tcx` has access to. Types are always canonicalized and interned (so we never -allocate exactly the same type twice). - -> NB. Because types are interned, it is possible to compare them for equality efficiently using `==` -> – however, this is almost never what you want to do unless you happen to be hashing and looking -> for duplicates. This is because often in Rust there are multiple ways to represent the same type, -> particularly once inference is involved. If you are going to be testing for type equality, you -> probably need to start looking into the inference code to do it right. - -You can also find various common types in the `tcx` itself by accessing `tcx.types.bool`, -`tcx.types.char`, etc (see [`CommonTypes`] for more). - -[`CommonTypes`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/context/struct.CommonTypes.html - -## Beyond types: other kinds of arena-allocated data structures - -In addition to types, there are a number of other arena-allocated data structures that you can -allocate, and which are found in this module. Here are a few examples: - -- [`Substs`][subst], allocated with `mk_substs` – this will intern a slice of types, often used to - specify the values to be substituted for generics (e.g. `HashMap` would be represented - as a slice `&'tcx [tcx.types.i32, tcx.types.u32]`). -- [`TraitRef`], typically passed by value – a **trait reference** consists of a reference to a trait - along with its various type parameters (including `Self`), like `i32: Display` (here, the def-id - would reference the `Display` trait, and the substs would contain `i32`). Note that `def-id` is - defined and discussed in depth in the `AdtDef and DefId` section. -- [`Predicate`] defines something the trait system has to prove (see `traits` module). - -[subst]: ./generic_arguments.html#subst -[`TraitRef`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TraitRef.html -[`Predicate`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/enum.Predicate.html - -## Import conventions - -Although there is no hard and fast rule, the `ty` module tends to be used like so: - -```rust,ignore -use ty::{self, Ty, TyCtxt}; -``` - -In particular, since they are so common, the `Ty` and `TyCtxt` types are imported directly. Other -types are often referenced with an explicit `ty::` prefix (e.g. `ty::TraitRef<'tcx>`). But some -modules choose to import a larger or smaller set of names explicitly. - -## ADTs Representation - -Let's consider the example of a type like `MyStruct`, where `MyStruct` is defined like so: - -```rust,ignore -struct MyStruct { x: u32, y: T } -``` - -The type `MyStruct` would be an instance of `TyKind::Adt`: - -```rust,ignore -Adt(&'tcx AdtDef, SubstsRef<'tcx>) -// ------------ --------------- -// (1) (2) -// -// (1) represents the `MyStruct` part -// (2) represents the ``, or "substitutions" / generic arguments -``` - -There are two parts: - -- The [`AdtDef`][adtdef] references the struct/enum/union but without the values for its type - parameters. In our example, this is the `MyStruct` part *without* the argument `u32`. - - Note that in the HIR, structs, enums and unions are represented differently, but in `ty::Ty`, - they are all represented using `TyKind::Adt`. -- The [`SubstsRef`][substsref] is an interned list of values that are to be substituted for the - generic parameters. In our example of `MyStruct`, we would end up with a list like `[u32]`. - We’ll dig more into generics and substitutions in a little bit. - -[adtdef]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.AdtDef.html -[substsref]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/type.SubstsRef.html - -**`AdtDef` and `DefId`** - -For every type defined in the source code, there is a unique `DefId` (see [this -chapter](hir.md#identifiers-in-the-hir)). This includes ADTs and generics. In the `MyStruct` -definition we gave above, there are two `DefId`s: one for `MyStruct` and one for `T`. Notice that -the code above does not generate a new `DefId` for `u32` because it is not defined in that code (it -is only referenced). - -`AdtDef` is more or less a wrapper around `DefId` with lots of useful helper methods. There is -essentially a one-to-one relationship between `AdtDef` and `DefId`. You can get the `AdtDef` for a -`DefId` with the [`tcx.adt_def(def_id)` query][adtdefq]. The `AdtDef`s are all interned (as you can -see `'tcx` lifetime on it). - -[adtdefq]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.TyCtxt.html#method.adt_def - - -### Generics and substitutions - -Given a generic type `MyType`, we may want to swap out the generics `A, B, …` for some -other types (possibly other generics or concrete types). We do this a lot while doing type -inference, type checking, and trait solving. Conceptually, during these routines, we may find out -that one type is equal to another type and want to swap one out for the other and then swap that out -for another type and so on until we eventually get some concrete types (or an error). - -In rustc this is done using the `SubstsRef` that we mentioned above (“substs” = “substitutions”). -Conceptually, you can think of `SubstsRef` of a list of types that are to be substituted for the -generic type parameters of the ADT. - -`SubstsRef` is a type alias of `List>` (see [`List` rustdocs][list]). -[`GenericArg`] is essentially a space-efficient wrapper around [`GenericArgKind`], which is an enum -indicating what kind of generic the type parameter is (type, lifetime, or const). Thus, `SubstsRef` -is conceptually like a `&'tcx [GenericArgKind<'tcx>]` slice (but it is actually a `List`). - -[list]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.List.html -[`GenericArg`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/struct.GenericArg.html -[`GenericArgKind`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/enum.GenericArgKind.html - -So why do we use this `List` type instead of making it really a slice? It has the length "inline", -so `&List` is only 32 bits. As a consequence, it cannot be "subsliced" (that only works if the -length is out of line). - -This also implies that you can check two `List`s for equality via `==` (which would be not be -possible for ordinary slices). This is precisely because they never represent a "sub-list", only the -complete `List`, which has been hashed and interned. - -So pulling it all together, let’s go back to our example above: - -```rust,ignore -struct MyStruct -``` - -- There would be an `AdtDef` (and corresponding `DefId`) for `MyStruct`. -- There would be a `TyKind::Param` (and corresponding `DefId`) for `T` (more later). -- There would be a `SubstsRef` containing the list `[GenericArgKind::Type(Ty(T))]` - - The `Ty(T)` here is my shorthand for entire other `ty::Ty` that has `TyKind::Param`, which we - mentioned in the previous point. -- This is one `TyKind::Adt` containing the `AdtDef` of `MyStruct` with the `SubstsRef` above. - -Finally, we will quickly mention the -[`Generics`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/struct.Generics.html) type. It -is used to give information about the type parameters of a type. - -### Unsubstituted Generics - -So above, recall that in our example the `MyStruct` struct had a generic type `T`. When we are (for -example) type checking functions that use `MyStruct`, we will need to be able to refer to this type -`T` without actually knowing what it is. In general, this is true inside all generic definitions: we -need to be able to work with unknown types. This is done via `TyKind::Param` (which we mentioned in -the example above). - -Each `TyKind::Param` contains two things: the name and the index. In general, the index fully -defines the parameter and is used by most of the code. The name is included for debug print-outs. -There are two reasons for this. First, the index is convenient, it allows you to include into the -list of generic arguments when substituting. Second, the index is more robust. For example, you -could in principle have two distinct type parameters that use the same name, e.g. `impl Foo { -fn bar() { .. } }`, although the rules against shadowing make this difficult (but those language -rules could change in the future). - -The index of the type parameter is an integer indicating its order in the list of the type -parameters. Moreover, we consider the list to include all of the type parameters from outer scopes. -Consider the following example: - -```rust,ignore -struct Foo { - // A would have index 0 - // B would have index 1 - - .. // some fields -} -impl Foo { - fn method() { - // inside here, X, Y and Z are all in scope - // X has index 0 - // Y has index 1 - // Z has index 2 - } -} -``` - -When we are working inside the generic definition, we will use `TyKind::Param` just like any other -`TyKind`; it is just a type after all. However, if we want to use the generic type somewhere, then -we will need to do substitutions. - -For example suppose that the `Foo` type from the previous example has a field that is a -`Vec`. Observe that `Vec` is also a generic type. We want to tell the compiler that the type -parameter of `Vec` should be replaced with the `A` type parameter of `Foo`. We do that with -substitutions: - -```rust,ignore -struct Foo { // Adt(Foo, &[Param(0), Param(1)]) - x: Vec, // Adt(Vec, &[Param(0)]) - .. -} - -fn bar(foo: Foo) { // Adt(Foo, &[u32, f32]) - let y = foo.x; // Vec => Vec -} -``` - -This example has a few different substitutions: - -- In the definition of `Foo`, in the type of the field `x`, we replace `Vec`'s type parameter with - `Param(0)`, the first parameter of `Foo`, so that the type of `x` is `Vec`. -- In the function `bar`, we specify that we want a `Foo`. This means that we will - substitute `Param(0)` and `Param(1)` with `u32` and `f32`. -- In the body of `bar`, we access `foo.x`, which has type `Vec`, but `Param(0)` has been - substituted for `u32`, so `foo.x` has type `Vec`. - -Let’s look a bit more closely at that last substitution to see why we use indexes. If we want to -find the type of `foo.x`, we can get generic type of `x`, which is `Vec`. Now we can take -the index `0` and use it to find the right type substitution: looking at `Foo`'s `SubstsRef`, we -have the list `[u32, f32]` , since we want to replace index `0`, we take the 0-th index of this -list, which is `u32`. Voila! - -You may have a couple of followup questions… - - **`type_of`** How do we get the “generic type of `x`"? You can get the type of pretty much anything - with the `tcx.type_of(def_id)` query. In this case, we would pass the `DefId` of the field `x`. - The `type_of` query always returns the definition with the generics that are in scope of the - definition. For example, `tcx.type_of(def_id_of_my_struct)` would return the “self-view” of - `MyStruct`: `Adt(Foo, &[Param(0), Param(1)])`. - -**`subst`** How do we actually do the substitutions? There is a function for that too! You use -[`subst`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/trait.Subst.html) to -replace a `SubstRef` with another list of types. - -[Here is an example of actually using `subst` in the compiler][substex]. The exact details are not -too important, but in this piece of code, we happen to be converting from the `rustc_hir::Ty` to -a real `ty::Ty`. You can see that we first get some substitutions (`substs`). Then we call -`type_of` to get a type and call `ty.subst(substs)` to get a new version of `ty` with -the substitutions made. - -[substex]: https://github.com/rust-lang/rust/blob/597f432489f12a3f33419daa039ccef11a12c4fd/src/librustc_typeck/astconv.rs#L942-L953 - -**Note on indices:** It is possible for the indices in `Param` to not match with what we expect. For -example, the index could be out of bounds or it could be the index of a lifetime when we were -expecting a type. These sorts of errors would be caught earlier in the compiler when translating -from a `rustc_hir::Ty` to a `ty::Ty`. If they occur later, that is a compiler bug. - -### `TypeFoldable` and `TypeFolder` - -How is this `subst` query actually implemented? As you can imagine, we might want to do -substitutions on a lot of different things. For example, we might want to do a substitution directly -on a type like we did with `Vec` above. But we might also have a more complex type with other types -nested inside that also need substitutions. - -The answer is a couple of traits: -[`TypeFoldable`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/fold/trait.TypeFoldable.html) -and -[`TypeFolder`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/fold/trait.TypeFolder.html). - -- `TypeFoldable` is implemented by types that embed type information. It allows you to recursively - process the contents of the `TypeFoldable` and do stuff to them. -- `TypeFolder` defines what you want to do with the types you encounter while processing the - `TypeFoldable`. - -For example, the `TypeFolder` trait has a method -[`fold_ty`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/fold/trait.TypeFolder.html#method.fold_ty) -that takes a type as input a type and returns a new type as a result. `TypeFoldable` invokes the -`TypeFolder` `fold_foo` methods on itself, giving the `TypeFolder` access to its contents (the -types, regions, etc that are contained within). - -You can think of it with this analogy to the iterator combinators we have come to love in rust: - -```rust,ignore -vec.iter().map(|e1| foo(e2)).collect() -// ^^^^^^^^^^^^ analogous to `TypeFolder` -// ^^^ analogous to `Typefoldable` -``` - -So to reiterate: - -- `TypeFolder` is a trait that defines a “map” operation. -- `TypeFoldable` is a trait that is implemented by things that embed types. - -In the case of `subst`, we can see that it is implemented as a `TypeFolder`: -[`SubstFolder`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ty/subst/struct.SubstFolder.html). -Looking at its implementation, we see where the actual substitutions are happening. - -However, you might also notice that the implementation calls this `super_fold_with` method. What is -that? It is a method of `TypeFoldable`. Consider the following `TypeFoldable` type `MyFoldable`: - -```rust,ignore -struct MyFoldable<'tcx> { - def_id: DefId, - ty: Ty<'tcx>, -} -``` - -The `TypeFolder` can call `super_fold_with` on `MyFoldable` if it just wants to replace some of the -fields of `MyFoldable` with new values. If it instead wants to replace the whole `MyFoldable` with a -different one, it would call `fold_with` instead (a different method on `TypeFoldable`). - -In almost all cases, we don’t want to replace the whole struct; we only want to replace `ty::Ty`s in -the struct, so usually we call `super_fold_with`. A typical implementation that `MyFoldable` could -have might do something like this: - -```rust,ignore -my_foldable: MyFoldable<'tcx> -my_foldable.subst(..., subst) - -impl TypeFoldable for MyFoldable { - fn super_fold_with(&self, folder: &mut impl TypeFolder<'tcx>) -> MyFoldable { - MyFoldable { - def_id: self.def_id.fold_with(folder), - ty: self.ty.fold_with(folder), - } - } - - fn super_visit_with(..) { } -} -``` - -Notice that here, we implement `super_fold_with` to go over the fields of `MyFoldable` and call -`fold_with` on *them*. That is, a folder may replace `def_id` and `ty`, but not the whole -`MyFoldable` struct. - -Here is another example to put things together: suppose we have a type like `Vec>`. The -`ty::Ty` would look like: `Adt(Vec, &[Adt(Vec, &[Param(X)])])`. If we want to do `subst(X => u32)`, -then we would first look at the overall type. We would see that there are no substitutions to be -made at the outer level, so we would descend one level and look at `Adt(Vec, &[Param(X)])`. There -are still no substitutions to be made here, so we would descend again. Now we are looking at -`Param(X)`, which can be substituted, so we replace it with `u32`. We can’t descend any more, so we -are done, and the overall result is `Adt(Vec, &[Adt(Vec, &[u32])])`. - -One last thing to mention: often when folding over a `TypeFoldable`, we don’t want to change most -things. We only want to do something when we reach a type. That means there may be a lot of -`TypeFoldable` types whose implementations basically just forward to their fields’ `TypeFoldable` -implementations. Such implementations of `TypeFoldable` tend to be pretty tedious to write by hand. -For this reason, there is a `derive` macro that allows you to `#![derive(TypeFoldable)]`. It is -defined -[here](https://github.com/rust-lang/rust/blob/master/src/librustc_macros/src/type_foldable.rs). - -**`subst`** In the case of substitutions the [actual -folder](https://github.com/rust-lang/rust/blob/04e69e4f4234beb4f12cc76dcc53e2cc4247a9be/src/librustc/ty/subst.rs#L467-L482) -is going to be doing the indexing we’ve already mentioned. There we define a `Folder` and call -`fold_with` on the `TypeFoldable` to process yourself. Then -[fold_ty](https://github.com/rust-lang/rust/blob/04e69e4f4234beb4f12cc76dcc53e2cc4247a9be/src/librustc/ty/subst.rs#L545-L573) -the method that process each type it looks for a `ty::Param` and for those it replaces it for -something from the list of substitutions, otherwise recursively process the type. To replace it, -calls -[ty_for_param](https://github.com/rust-lang/rust/blob/04e69e4f4234beb4f12cc76dcc53e2cc4247a9be/src/librustc/ty/subst.rs#L589-L624) -and all that does is index into the list of substitutions with the index of the `Param`. - -## Type errors - -There is a `TyKind::Error` that is produced when the user makes a type error. The idea is that -we would propagate this type and suppress other errors that come up due to it so as not to overwhelm -the user with cascading compiler error messages. - -There is an **important invariant** for `TyKind::Error`. You should **never** return the 'error -type' unless you **know** that an error has already been reported to the user. This is usually -because (a) you just reported it right there or (b) you are propagating an existing Error type (in -which case the error should've been reported when that error type was produced). - -It's important to maintain this invariant because the whole point of the `Error` type is to suppress -other errors -- i.e., we don't report them. If we were to produce an `Error` type without actually -emitting an error to the user, then this could cause later errors to be suppressed, and the -compilation might inadvertently succeed! - -Sometimes there is a third case. You believe that an error has been reported, but you believe it -would've been reported earlier in the compilation, not locally. In that case, you can invoke -[`delay_span_bug`] This will make a note that you expect compilation to yield an error -- if however -compilation should succeed, then it will trigger a compiler bug report. - -[`delay_span_bug`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_session/struct.Session.html#method.delay_span_bug - -## Question: Why not substitute “inside” the `AdtDef`? - -Recall that we represent a generic struct with `(AdtDef, substs)`. So why bother with this scheme? - -Well, the alternate way we could have choosen to represent types would be to always create a new, -fully-substituted form of the `AdtDef` where all the types are already substituted. This seems like -less of a hassle. However, the `(AdtDef, substs)` scheme has some advantages over this. - -First, `(AdtDef, substs)` scheme has an efficiency win: - -```rust,ignore -struct MyStruct { - ... 100s of fields ... -} - -// Want to do: MyStruct ==> MyStruct -``` - -in an example like this, we can subst from `MyStruct` to `MyStruct` (and so on) very cheaply, -by just replacing the one reference to `A` with `B`. But if we eagerly substituted all the fields, -that could be a lot more work because we might have to go through all of the fields in the `AdtDef` -and update all of their types. - -A bit more deeply, this corresponds to structs in Rust being [*nominal* types][nominal] — which -means that they are defined by their *name* (and that their contents are then indexed from the -definition of that name, and not carried along “within” the type itself). - -[nominal]: https://en.wikipedia.org/wiki/Nominal_type_system diff --git a/src/doc/rustc-ux-guidelines.md b/src/doc/rustc-ux-guidelines.md index dfd8e9db3c..b626923bcb 100644 --- a/src/doc/rustc-ux-guidelines.md +++ b/src/doc/rustc-ux-guidelines.md @@ -62,7 +62,7 @@ for details on how to format and write long error codes. * All of them are accessible [online](http://doc.rust-lang.org/error-index.html), which are auto-generated from rustc source code in different places: [librustc](https://github.com/rust-lang/rust/blob/master/src/librustc/error_codes.rs), - [libsyntax](https://github.com/rust-lang/rust/blob/master/src/libsyntax/error_codes.rs), + [librustc_ast](https://github.com/rust-lang/rust/blob/master/src/librustc_ast/error_codes.rs), [librustc_borrowck](https://github.com/rust-lang/rust/blob/master/src/librustc_borrowck/error_codes.rs), [librustc_metadata](https://github.com/rust-lang/rust/blob/master/src/librustc_metadata/error_codes.rs), [librustc_mir](https://github.com/rust-lang/rust/blob/master/src/librustc_mir/error_codes.rs), diff --git a/src/doc/rustc/src/command-line-arguments.md b/src/doc/rustc/src/command-line-arguments.md index 577d03d103..7a7838d965 100644 --- a/src/doc/rustc/src/command-line-arguments.md +++ b/src/doc/rustc/src/command-line-arguments.md @@ -146,6 +146,7 @@ The valid types of print values are: - `crate-name` — The name of the crate. - `file-names` — The names of the files created by the `link` emit kind. - `sysroot` — Path to the sysroot. +- `target-libdir` - Path to the target libdir. - `cfg` — List of cfg values. See [conditional compilation] for more information about cfg values. - `target-list` — List of known targets. The target may be selected with the @@ -215,21 +216,29 @@ This controls which [target](targets/index.md) to produce. This flag will set which lints should be set to the [warn level](lints/levels.md#warn). +_Note:_ The order of these lint level arguments is taken into account, see [lint level via compiler flag](lints/levels.md#via-compiler-flag) for more information. + ## `-A`: set lint allowed This flag will set which lints should be set to the [allow level](lints/levels.md#allow). +_Note:_ The order of these lint level arguments is taken into account, see [lint level via compiler flag](lints/levels.md#via-compiler-flag) for more information. + ## `-D`: set lint denied This flag will set which lints should be set to the [deny level](lints/levels.md#deny). +_Note:_ The order of these lint level arguments is taken into account, see [lint level via compiler flag](lints/levels.md#via-compiler-flag) for more information. + ## `-F`: set lint forbidden This flag will set which lints should be set to the [forbid level](lints/levels.md#forbid). +_Note:_ The order of these lint level arguments is taken into account, see [lint level via compiler flag](lints/levels.md#via-compiler-flag) for more information. + ## `-Z`: set unstable options diff --git a/src/doc/rustc/src/lints/levels.md b/src/doc/rustc/src/lints/levels.md index 2944e86566..3cfe2f698f 100644 --- a/src/doc/rustc/src/lints/levels.md +++ b/src/doc/rustc/src/lints/levels.md @@ -164,6 +164,18 @@ And of course, you can mix these four flags together: $ rustc lib.rs --crate-type=lib -D missing-docs -A unused-variables ``` +The order of these command line arguments is taken into account. The following allows the `unused-variables` lint, because it is the last argument for that lint: + +```bash +$ rustc lib.rs --crate-type=lib -D unused-variables -A unused-variables +``` + +You can make use of this behavior by overriding the level of one specific lint out of a group of lints. The following example denies all the lints in the `unused` group, but explicitly allows the `unused-variables` lint in that group: + +```bash +$ rustc lib.rs --crate-type=lib -D unused -A unused-variables +``` + ### Via an attribute You can also modify the lint level with a crate-wide attribute: diff --git a/src/doc/rustdoc/book.toml b/src/doc/rustdoc/book.toml new file mode 100644 index 0000000000..ba30c10766 --- /dev/null +++ b/src/doc/rustdoc/book.toml @@ -0,0 +1,4 @@ +[book] +authors = ["The Rust Project Developers"] +src = "src" +title = "The rustdoc book" diff --git a/src/doc/rustdoc/src/the-doc-attribute.md b/src/doc/rustdoc/src/the-doc-attribute.md index 80ac405eb2..ef143c8727 100644 --- a/src/doc/rustdoc/src/the-doc-attribute.md +++ b/src/doc/rustdoc/src/the-doc-attribute.md @@ -39,7 +39,7 @@ crate level, and ones that are useful at the item level. ## At the crate level -These options control how the docs look at a macro level. +These options control how the docs look at a crate level. ### `html_favicon_url` diff --git a/src/doc/rustdoc/src/unstable-features.md b/src/doc/rustdoc/src/unstable-features.md index a48526d39f..f704fe8e09 100644 --- a/src/doc/rustdoc/src/unstable-features.md +++ b/src/doc/rustdoc/src/unstable-features.md @@ -138,27 +138,6 @@ Book][unstable-doc-cfg] and [its tracking issue][issue-doc-cfg]. [unstable-doc-cfg]: ../unstable-book/language-features/doc-cfg.html [issue-doc-cfg]: https://github.com/rust-lang/rust/issues/43781 -### Adding your trait to the "Important Traits" dialog - -Rustdoc keeps a list of a few traits that are believed to be "fundamental" to a given type when -implemented on it. These traits are intended to be the primary interface for their types, and are -often the only thing available to be documented on their types. For this reason, Rustdoc will track -when a given type implements one of these traits and call special attention to it when a function -returns one of these types. This is the "Important Traits" dialog, visible as a circle-i button next -to the function, which, when clicked, shows the dialog. - -In the standard library, the traits that qualify for inclusion are `Iterator`, `io::Read`, and -`io::Write`. However, rather than being implemented as a hard-coded list, these traits have a -special marker attribute on them: `#[doc(spotlight)]`. This means that you could apply this -attribute to your own trait to include it in the "Important Traits" dialog in documentation. - -The `#[doc(spotlight)]` attribute currently requires the `#![feature(doc_spotlight)]` feature gate. -For more information, see [its chapter in the Unstable Book][unstable-spotlight] and [its tracking -issue][issue-spotlight]. - -[unstable-spotlight]: ../unstable-book/language-features/doc-spotlight.html -[issue-spotlight]: https://github.com/rust-lang/rust/issues/45040 - ### Exclude certain dependencies from documentation The standard library uses several dependencies which, in turn, use several types and traits from the @@ -453,7 +432,7 @@ override `ignore`. ### `--runtool`, `--runtool-arg`: program to run tests with; args to pass to it -Using thses options looks like this: +Using these options looks like this: ```bash $ rustdoc src/lib.rs -Z unstable-options --runtool runner --runtool-arg --do-thing --runtool-arg --do-other-thing diff --git a/src/doc/unstable-book/src/compiler-flags/control-flow-guard.md b/src/doc/unstable-book/src/compiler-flags/control-flow-guard.md new file mode 100644 index 0000000000..f871df4625 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/control-flow-guard.md @@ -0,0 +1,34 @@ +# `control_flow_guard` + +The tracking issue for this feature is: [#68793](https://github.com/rust-lang/rust/issues/68793). + +------------------------ + +The `-Zcontrol_flow_guard=checks` compiler flag enables the Windows [Control Flow Guard][cfguard-docs] platform security feature. When enabled, the compiler outputs a list of valid indirect call targets, and inserts runtime checks on all indirect jump instructions to ensure that the destination is in the list of valid call targets. + +[cfguard-docs]: https://docs.microsoft.com/en-us/windows/win32/secbp/control-flow-guard + +For testing purposes, the `-Zcontrol_flow_guard=nochecks` compiler flag can be used to emit only the list of valid call targets, but not the runtime checks. + +It is strongly recommended to also enable Control Flow Guard checks in all linked libraries, including the standard library. + +To enable Control Flow Guard in the standard library, you can use the [cargo `-Zbuild-std` functionality][build-std] to recompile the standard library with the same configuration options as the main program. + +[build-std]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-std + +For example: +```cmd +rustup toolchain install --force nightly +rustup component add rust-src +SET RUSTFLAGS=-Zcontrol_flow_guard=checks +cargo +nightly build -Z build-std --target x86_64-pc-windows-msvc +``` + +```PowerShell +rustup toolchain install --force nightly +rustup component add rust-src +$Env:RUSTFLAGS = "-Zcontrol_flow_guard=checks" +cargo +nightly build -Z build-std --target x86_64-pc-windows-msvc +``` + +Alternatively, if you are building the standard library from source, you can set `control-flow-guard = true` in the config.toml file. diff --git a/src/doc/unstable-book/src/compiler-flags/sanitizer.md b/src/doc/unstable-book/src/compiler-flags/sanitizer.md index cbb90bd3bb..414ac7e63a 100644 --- a/src/doc/unstable-book/src/compiler-flags/sanitizer.md +++ b/src/doc/unstable-book/src/compiler-flags/sanitizer.md @@ -93,10 +93,84 @@ Shadow byte legend (one shadow byte represents 8 application bytes): ==10029==ABORTING ``` +Use of a stack object after its scope has already ended: + +```shell +$ cat b.rs +static mut P: *mut usize = std::ptr::null_mut(); + +fn main() { + unsafe { + { + let mut x = 0; + P = &mut x; + } + std::ptr::write_volatile(P, 123); + } +} +$ rustc -Zsanitizer=address b.rs +$./b +================================================================= +==424427==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7fff67be6be0 at pc 0x5647a3ea4658 bp 0x7fff67be6b90 sp 0x7fff67be6b88 +WRITE of size 8 at 0x7fff67be6be0 thread T0 + #0 0x5647a3ea4657 in core::ptr::write_volatile::h4b04601757d0376d (/tmp/b+0xb8657) + #1 0x5647a3ea4432 in b::main::h5574a756e615c9cf (/tmp/b+0xb8432) + #2 0x5647a3ea480b in std::rt::lang_start::_$u7b$$u7b$closure$u7d$$u7d$::hd57e7ee01866077e (/tmp/b+0xb880b) + #3 0x5647a3eab412 in std::panicking::try::do_call::he0421ca82dd11ba3 (.llvm.8083791802951296215) (/tmp/b+0xbf412) + #4 0x5647a3eacb26 in __rust_maybe_catch_panic (/tmp/b+0xc0b26) + #5 0x5647a3ea5b66 in std::rt::lang_start_internal::h19bc96b28f670a64 (/tmp/b+0xb9b66) + #6 0x5647a3ea4788 in std::rt::lang_start::h642d10b4b6965fb8 (/tmp/b+0xb8788) + #7 0x5647a3ea449a in main (/tmp/b+0xb849a) + #8 0x7fd1d18b3bba in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26bba) + #9 0x5647a3df7299 in _start (/tmp/b+0xb299) + +Address 0x7fff67be6be0 is located in stack of thread T0 at offset 32 in frame + #0 0x5647a3ea433f in b::main::h5574a756e615c9cf (/tmp/b+0xb833f) + + This frame has 1 object(s): + [32, 40) 'x' <== Memory access at offset 32 is inside this variable +HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork + (longjmp and C++ exceptions *are* supported) +SUMMARY: AddressSanitizer: stack-use-after-scope (/tmp/b+0xb8657) in core::ptr::write_volatile::h4b04601757d0376d +Shadow bytes around the buggy address: + 0x10006cf74d20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74d30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74d40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74d50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74d60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +=>0x10006cf74d70: 00 00 00 00 00 00 00 00 f1 f1 f1 f1[f8]f3 f3 f3 + 0x10006cf74d80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74d90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74da0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74db0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x10006cf74dc0: f1 f1 f1 f1 00 f3 f3 f3 00 00 00 00 00 00 00 00 +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb + Shadow gap: cc +==424427==ABORTING +``` + ## MemorySanitizer Use of uninitialized memory. Note that we are using `-Zbuild-std` to instrument -standard library, and passing `-msan-track-origins=2` to the LLVM to track +the standard library, and passing `-Zsanitizer-track-origins` to track the origins of uninitialized memory: ```shell @@ -111,7 +185,15 @@ fn main() { } } -$ env RUSTFLAGS="-Zsanitizer=memory -Cllvm-args=-msan-track-origins=2" cargo -Zbuild-std run --target x86_64-unknown-linux-gnu +$ export \ + CC=clang \ + CXX=clang++ \ + CFLAGS='-fsanitize=memory -fsanitize-memory-track-origins' \ + CXXFLAGS='-fsanitize=memory -fsanitize-memory-track-origins' \ + RUSTFLAGS='-Zsanitizer=memory -Zsanitizer-memory-track-origins' \ + RUSTDOCFLAGS='-Zsanitizer=memory -Zsanitizer-memory-track-origins' +$ cargo clean +$ cargo -Zbuild-std run --target x86_64-unknown-linux-gnu ==9416==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x560c04f7488a in core::fmt::num::imp::fmt_u64::haa293b0b098501ca $RUST/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/src/rust/src/libcore/fmt/num.rs:202:16 ... diff --git a/src/doc/unstable-book/src/compiler-flags/self-profile-events.md b/src/doc/unstable-book/src/compiler-flags/self-profile-events.md new file mode 100644 index 0000000000..3ce18743be --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/self-profile-events.md @@ -0,0 +1,74 @@ +# `self-profile-events` + +--------------------- + +The `-Zself-profile-events` compiler flag controls what events are recorded by the self-profiler when it is enabled via the `-Zself-profile` flag. + +This flag takes a comma delimited list of event types to record. + +For example: + +```console +$ rustc -Zself-profile -Zself-profile-events=default,args +``` + +## Event types + +- `query-provider` + - Traces each query used internally by the compiler. + +- `generic-activity` + - Traces other parts of the compiler not covered by the query system. + +- `query-cache-hit` + - Adds tracing information that records when the in-memory query cache is "hit" and does not need to re-execute a query which has been cached. + - Disabled by default because this significantly increases the trace file size. + +- `query-blocked` + - Tracks time that a query tries to run but is blocked waiting on another thread executing the same query to finish executing. + - Query blocking only occurs when the compiler is built with parallel mode support. + +- `incr-cache-load` + - Tracks time that is spent loading and deserializing query results from the incremental compilation on-disk cache. + +- `query-keys` + - Adds a serialized representation of each query's query key to the tracing data. + - Disabled by default because this significantly increases the trace file size. + +- `function-args` + - Adds additional tracing data to some `generic-activity` events. + - Disabled by default for parity with `query-keys`. + +- `llvm` + - Adds tracing information about LLVM passes and codegeneration. + - Disabled by default because this only works when `-Znew-llvm-pass-manager` is enabled. + +## Event synonyms + +- `none` + - Disables all events. + Equivalent to the self-profiler being disabled. + +- `default` + - The default set of events which stikes a balance between providing detailed tracing data and adding additional overhead to the compilation. + +- `args` + - Equivalent to `query-keys` and `function-args`. + +- `all` + - Enables all events. + +## Examples + +Enable the profiler and capture the default set of events (both invocations are equivalent): + +```console +$ rustc -Zself-profile +$ rustc -Zself-profile -Zself-profile-events=default +``` + +Enable the profiler and capture the default events and their arguments: + +```console +$ rustc -Zself-profile -Zself-profile-events=default,args +``` diff --git a/src/doc/unstable-book/src/compiler-flags/self-profile.md b/src/doc/unstable-book/src/compiler-flags/self-profile.md new file mode 100644 index 0000000000..6de1c774f7 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/self-profile.md @@ -0,0 +1,47 @@ +# `self-profile` + +-------------------- + +The `-Zself-profile` compiler flag enables rustc's internal profiler. +When enabled, the compiler will output three binary files in the specified directory (or the current working directory if no directory is specified). +These files can be analyzed by using the tools in the [`measureme`] repository. + +To control the data recorded in the trace files, use the `-Zself-profile-events` flag. + +For example: + +First, run a compilation session and provide the `-Zself-profile` flag: + +```console +$ rustc --crate-name foo -Zself-profile` +``` + +This will generate three files in the working directory such as: + +- `foo-1234.events` +- `foo-1234.string_data` +- `foo-1234.string_index` + +Where `foo` is the name of the crate and `1234` is the process id of the rustc process. + +To get a summary of where the compiler is spending its time: + +```console +$ ../measureme/target/release/summarize summarize foo-1234 +``` + +To generate a flamegraph of the same data: + +```console +$ ../measureme/target/release/inferno foo-1234 +``` + +To dump the event data in a Chromium-profiler compatible format: + +```console +$ ../measureme/target/release/crox foo-1234 +``` + +For more information, consult the [`measureme`] documentation. + +[`measureme`]: https://github.com/rust-lang/measureme.git diff --git a/src/doc/unstable-book/src/language-features/const-eval-limit.md b/src/doc/unstable-book/src/language-features/const-eval-limit.md new file mode 100644 index 0000000000..df68e83bca --- /dev/null +++ b/src/doc/unstable-book/src/language-features/const-eval-limit.md @@ -0,0 +1,7 @@ +# `const_eval_limit` + +The tracking issue for this feature is: [#67217] + +[#67217]: https://github.com/rust-lang/rust/issues/67217 + +The `const_eval_limit` allows someone to limit the evaluation steps the CTFE undertakes to evaluate a `const fn`. diff --git a/src/doc/unstable-book/src/language-features/const-in-array-repeat-expressions.md b/src/doc/unstable-book/src/language-features/const-in-array-repeat-expressions.md index 09d1b19b4c..940916944b 100644 --- a/src/doc/unstable-book/src/language-features/const-in-array-repeat-expressions.md +++ b/src/doc/unstable-book/src/language-features/const-in-array-repeat-expressions.md @@ -2,7 +2,7 @@ The tracking issue for this feature is: [#49147] -[#44109]: https://github.com/rust-lang/rust/issues/49147 +[#49147]: https://github.com/rust-lang/rust/issues/49147 ------------------------ diff --git a/src/doc/unstable-book/src/language-features/doc-spotlight.md b/src/doc/unstable-book/src/language-features/doc-spotlight.md deleted file mode 100644 index 8117755fef..0000000000 --- a/src/doc/unstable-book/src/language-features/doc-spotlight.md +++ /dev/null @@ -1,30 +0,0 @@ -# `doc_spotlight` - -The tracking issue for this feature is: [#45040] - -The `doc_spotlight` feature allows the use of the `spotlight` parameter to the `#[doc]` attribute, -to "spotlight" a specific trait on the return values of functions. Adding a `#[doc(spotlight)]` -attribute to a trait definition will make rustdoc print extra information for functions which return -a type that implements that trait. This attribute is applied to the `Iterator`, `io::Read`, and -`io::Write` traits in the standard library. - -You can do this on your own traits, like this: - -``` -#![feature(doc_spotlight)] - -#[doc(spotlight)] -pub trait MyTrait {} - -pub struct MyStruct; -impl MyTrait for MyStruct {} - -/// The docs for this function will have an extra line about `MyStruct` implementing `MyTrait`, -/// without having to write that yourself! -pub fn my_fn() -> MyStruct { MyStruct } -``` - -This feature was originally implemented in PR [#45039]. - -[#45040]: https://github.com/rust-lang/rust/issues/45040 -[#45039]: https://github.com/rust-lang/rust/pull/45039 diff --git a/src/doc/unstable-book/src/language-features/generators.md b/src/doc/unstable-book/src/language-features/generators.md index 97cf58e57e..8bc62418b3 100644 --- a/src/doc/unstable-book/src/language-features/generators.md +++ b/src/doc/unstable-book/src/language-features/generators.md @@ -37,11 +37,11 @@ fn main() { return "foo" }; - match Pin::new(&mut generator).resume() { + match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(1) => {} _ => panic!("unexpected value from resume"), } - match Pin::new(&mut generator).resume() { + match Pin::new(&mut generator).resume(()) { GeneratorState::Complete("foo") => {} _ => panic!("unexpected value from resume"), } @@ -71,9 +71,9 @@ fn main() { }; println!("1"); - Pin::new(&mut generator).resume(); + Pin::new(&mut generator).resume(()); println!("3"); - Pin::new(&mut generator).resume(); + Pin::new(&mut generator).resume(()); println!("5"); } ``` @@ -92,10 +92,10 @@ The `Generator` trait in `std::ops` currently looks like: # use std::ops::GeneratorState; # use std::pin::Pin; -pub trait Generator { +pub trait Generator { type Yield; type Return; - fn resume(self: Pin<&mut Self>) -> GeneratorState; + fn resume(self: Pin<&mut Self>, resume: R) -> GeneratorState; } ``` @@ -152,10 +152,6 @@ closure-like semantics. Namely: * Whenever a generator is dropped it will drop all captured environment variables. -Note that unlike closures, generators at this time cannot take any arguments. -That is, generators must always look like `|| { ... }`. This restriction may be -lifted at a future date, the design is ongoing! - ### Generators as state machines In the compiler, generators are currently compiled as state machines. Each @@ -179,8 +175,8 @@ fn main() { return ret }; - Pin::new(&mut generator).resume(); - Pin::new(&mut generator).resume(); + Pin::new(&mut generator).resume(()); + Pin::new(&mut generator).resume(()); } ``` @@ -205,7 +201,7 @@ fn main() { type Yield = i32; type Return = &'static str; - fn resume(mut self: Pin<&mut Self>) -> GeneratorState { + fn resume(mut self: Pin<&mut Self>, resume: ()) -> GeneratorState { use std::mem; match mem::replace(&mut *self, __Generator::Done) { __Generator::Start(s) => { @@ -228,8 +224,8 @@ fn main() { __Generator::Start(ret) }; - Pin::new(&mut generator).resume(); - Pin::new(&mut generator).resume(); + Pin::new(&mut generator).resume(()); + Pin::new(&mut generator).resume(()); } ``` diff --git a/src/doc/unstable-book/src/language-features/impl-trait-in-bindings.md b/src/doc/unstable-book/src/language-features/impl-trait-in-bindings.md index 896465cf64..5c6aa912c1 100644 --- a/src/doc/unstable-book/src/language-features/impl-trait-in-bindings.md +++ b/src/doc/unstable-book/src/language-features/impl-trait-in-bindings.md @@ -1,8 +1,8 @@ # `impl_trait_in_bindings` -The tracking issue for this feature is: [#34511] +The tracking issue for this feature is: [#63065] -[#34511]: https://github.com/rust-lang/rust/issues/34511 +[#63065]: https://github.com/rust-lang/rust/issues/63065 ------------------------ diff --git a/src/doc/unstable-book/src/language-features/link-cfg.md b/src/doc/unstable-book/src/language-features/link-cfg.md new file mode 100644 index 0000000000..ee0fd5bf86 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/link-cfg.md @@ -0,0 +1,5 @@ +# `link_cfg` + +This feature is internal to the Rust compiler and is not intended for general use. + +------------------------ diff --git a/src/doc/unstable-book/src/language-features/marker-trait-attr.md b/src/doc/unstable-book/src/language-features/marker-trait-attr.md index dedc7d3015..be350cd616 100644 --- a/src/doc/unstable-book/src/language-features/marker-trait-attr.md +++ b/src/doc/unstable-book/src/language-features/marker-trait-attr.md @@ -21,7 +21,7 @@ when they'd need to do the same thing for every type anyway). impl CheapToClone for T {} -// These could potentally overlap with the blanket implementation above, +// These could potentially overlap with the blanket implementation above, // so are only allowed because CheapToClone is a marker trait. impl CheapToClone for (T, U) {} impl CheapToClone for std::ops::Range {} diff --git a/src/doc/unstable-book/src/language-features/no-sanitize.md b/src/doc/unstable-book/src/language-features/no-sanitize.md new file mode 100644 index 0000000000..28c683934d --- /dev/null +++ b/src/doc/unstable-book/src/language-features/no-sanitize.md @@ -0,0 +1,29 @@ +# `no_sanitize` + +The tracking issue for this feature is: [#39699] + +[#39699]: https://github.com/rust-lang/rust/issues/39699 + +------------------------ + +The `no_sanitize` attribute can be used to selectively disable sanitizer +instrumentation in an annotated function. This might be useful to: avoid +instrumentation overhead in a performance critical function, or avoid +instrumenting code that contains constructs unsupported by given sanitizer. + +The precise effect of this annotation depends on particular sanitizer in use. +For example, with `no_sanitize(thread)`, the thread sanitizer will no longer +instrument non-atomic store / load operations, but it will instrument atomic +operations to avoid reporting false positives and provide meaning full stack +traces. + +## Examples + +``` rust +#![feature(no_sanitize)] + +#[no_sanitize(address)] +fn foo() { + // ... +} +``` diff --git a/src/doc/unstable-book/src/language-features/plugin.md b/src/doc/unstable-book/src/language-features/plugin.md index 495cdee62c..47ac986c22 100644 --- a/src/doc/unstable-book/src/language-features/plugin.md +++ b/src/doc/unstable-book/src/language-features/plugin.md @@ -23,7 +23,7 @@ mechanics of defining and loading a plugin. In the vast majority of cases, a plugin should *only* be used through `#![plugin]` and not through an `extern crate` item. Linking a plugin would -pull in all of libsyntax and librustc as dependencies of your crate. This is +pull in all of librustc_ast and librustc as dependencies of your crate. This is generally unwanted unless you are building another plugin. The usual practice is to put compiler plugins in their own crate, separate from @@ -42,7 +42,7 @@ that warns about any item named `lintme`. #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] -extern crate syntax; +extern crate rustc_ast; // Load rustc as a plugin to get macros #[macro_use] @@ -52,7 +52,7 @@ extern crate rustc_driver; use rustc::lint::{EarlyContext, LintContext, LintPass, EarlyLintPass, EarlyLintPassObject, LintArray}; use rustc_driver::plugin::Registry; -use syntax::ast; +use rustc_ast::ast; declare_lint!(TEST_LINT, Warn, "Warn about items named 'lintme'"); diff --git a/src/doc/unstable-book/src/language-features/trait-alias.md b/src/doc/unstable-book/src/language-features/trait-alias.md index 4f2db04016..f1be053ddc 100644 --- a/src/doc/unstable-book/src/language-features/trait-alias.md +++ b/src/doc/unstable-book/src/language-features/trait-alias.md @@ -2,7 +2,7 @@ The tracking issue for this feature is: [#41517] -[#41417]: https://github.com/rust-lang/rust/issues/41517 +[#41517]: https://github.com/rust-lang/rust/issues/41517 ------------------------ diff --git a/src/doc/unstable-book/src/language-features/transparent-unions.md b/src/doc/unstable-book/src/language-features/transparent-unions.md index b731c9ea6d..9b39b89716 100644 --- a/src/doc/unstable-book/src/language-features/transparent-unions.md +++ b/src/doc/unstable-book/src/language-features/transparent-unions.md @@ -2,7 +2,7 @@ The tracking issue for this feature is [#60405] -[60405]: https://github.com/rust-lang/rust/issues/60405 +[#60405]: https://github.com/rust-lang/rust/issues/60405 ---- diff --git a/src/doc/unstable-book/src/library-features/allocator-api.md b/src/doc/unstable-book/src/library-features/allocator-api.md index e3969ace7e..9f045ce08a 100644 --- a/src/doc/unstable-book/src/library-features/allocator-api.md +++ b/src/doc/unstable-book/src/library-features/allocator-api.md @@ -9,7 +9,7 @@ The tracking issue for this feature is [#32838] Sometimes you want the memory for one collection to use a different allocator than the memory for another collection. In this case, replacing the global allocator is not a workable option. Instead, -you need to pass in an instance of an `Alloc` to each collection +you need to pass in an instance of an `AllocRef` to each collection for which you want a custom allocator. TBD diff --git a/src/doc/unstable-book/src/library-features/read-initializer.md b/src/doc/unstable-book/src/library-features/read-initializer.md deleted file mode 100644 index 898fe58eee..0000000000 --- a/src/doc/unstable-book/src/library-features/read-initializer.md +++ /dev/null @@ -1,7 +0,0 @@ -# `read_initializer` - -The tracking issue for this feature is: [#42788] - -[#0]: https://github.com/rust-lang/rust/issues/42788 - ------------------------- diff --git a/src/doc/unstable-book/src/library-features/tidy-test-never-used-anywhere-else.md b/src/doc/unstable-book/src/library-features/tidy-test-never-used-anywhere-else.md new file mode 100644 index 0000000000..c194d79a19 --- /dev/null +++ b/src/doc/unstable-book/src/library-features/tidy-test-never-used-anywhere-else.md @@ -0,0 +1,5 @@ +# `tidy_test_never_used_anywhere_else` + +This feature is internal to the Rust compiler and is not intended for general use. + +------------------------ diff --git a/src/etc/debugger_pretty_printers_common.py b/src/etc/debugger_pretty_printers_common.py index 385ce8efab..b3f8f50636 100644 --- a/src/etc/debugger_pretty_printers_common.py +++ b/src/etc/debugger_pretty_printers_common.py @@ -212,7 +212,6 @@ class Type(object): # REGULAR STRUCT return TYPE_KIND_REGULAR_STRUCT - def __classify_union(self): assert self.get_dwarf_type_kind() == DWARF_TYPE_CODE_UNION @@ -233,7 +232,6 @@ class Type(object): else: return TYPE_KIND_REGULAR_UNION - def __conforms_to_field_layout(self, expected_fields): actual_fields = self.get_fields() actual_field_count = len(actual_fields) @@ -363,6 +361,7 @@ def extract_tail_head_ptr_and_cap_from_std_vecdeque(vec_val): assert data_ptr.type.get_dwarf_type_kind() == DWARF_TYPE_CODE_PTR return (tail, head, data_ptr, capacity) + def extract_length_and_ptr_from_slice(slice_val): assert (slice_val.type.get_type_kind() == TYPE_KIND_SLICE or slice_val.type.get_type_kind() == TYPE_KIND_STR_SLICE) @@ -376,8 +375,10 @@ def extract_length_and_ptr_from_slice(slice_val): assert data_ptr.type.get_dwarf_type_kind() == DWARF_TYPE_CODE_PTR return (length, data_ptr) + UNQUALIFIED_TYPE_MARKERS = frozenset(["(", "[", "&", "*"]) + def extract_type_name(qualified_type_name): """Extracts the type name from a fully qualified path""" if qualified_type_name[0] in UNQUALIFIED_TYPE_MARKERS: @@ -393,6 +394,7 @@ def extract_type_name(qualified_type_name): else: return qualified_type_name[index + 2:] + try: compat_str = unicode # Python 2 except NameError: diff --git a/src/etc/dec2flt_table.py b/src/etc/dec2flt_table.py index 85395d2ecd..4979882ffe 100755 --- a/src/etc/dec2flt_table.py +++ b/src/etc/dec2flt_table.py @@ -14,7 +14,6 @@ is used because (u64, i16) has a ton of padding which would make the table even larger, and it's already uncomfortably large (6 KiB). """ from __future__ import print_function -import sys from math import ceil, log from fractions import Fraction from collections import namedtuple @@ -82,6 +81,7 @@ def error(f, e, z): ulp_err = abs_err / Fraction(2) ** z.exp return float(ulp_err) + HEADER = """ //! Tables of approximations of powers of ten. //! DO NOT MODIFY: Generated by `src/etc/dec2flt_table.py` diff --git a/src/etc/gdb_rust_pretty_printing.py b/src/etc/gdb_rust_pretty_printing.py index 5da01b96fa..0914c22eb1 100755 --- a/src/etc/gdb_rust_pretty_printing.py +++ b/src/etc/gdb_rust_pretty_printing.py @@ -9,7 +9,7 @@ import debugger_pretty_printers_common as rustpp if sys.version_info[0] >= 3: xrange = range -rust_enabled = 'set language rust' in gdb.execute('complete set language ru', to_string = True) +rust_enabled = 'set language rust' in gdb.execute('complete set language ru', to_string=True) # The btree pretty-printers fail in a confusing way unless # https://sourceware.org/bugzilla/show_bug.cgi?id=21763 is fixed. @@ -21,9 +21,10 @@ if _match: if int(_match.group(1)) > 8 or (int(_match.group(1)) == 8 and int(_match.group(2)) >= 1): gdb_81 = True -#=============================================================================== +# =============================================================================== # GDB Pretty Printing Module for Rust -#=============================================================================== +# =============================================================================== + class GdbType(rustpp.Type): @@ -133,39 +134,39 @@ def rust_pretty_printer_lookup_function(gdb_val): if type_kind == rustpp.TYPE_KIND_REGULAR_STRUCT: return RustStructPrinter(val, - omit_first_field = False, - omit_type_name = False, - is_tuple_like = False) + omit_first_field=False, + omit_type_name=False, + is_tuple_like=False) if type_kind == rustpp.TYPE_KIND_STRUCT_VARIANT: return RustStructPrinter(val, - omit_first_field = True, - omit_type_name = False, - is_tuple_like = False) + omit_first_field=True, + omit_type_name=False, + is_tuple_like=False) if type_kind == rustpp.TYPE_KIND_STR_SLICE: return RustStringSlicePrinter(val) if type_kind == rustpp.TYPE_KIND_TUPLE: return RustStructPrinter(val, - omit_first_field = False, - omit_type_name = True, - is_tuple_like = True) + omit_first_field=False, + omit_type_name=True, + is_tuple_like=True) if type_kind == rustpp.TYPE_KIND_TUPLE_STRUCT: return RustStructPrinter(val, - omit_first_field = False, - omit_type_name = False, - is_tuple_like = True) + omit_first_field=False, + omit_type_name=False, + is_tuple_like=True) if type_kind == rustpp.TYPE_KIND_CSTYLE_VARIANT: return RustCStyleVariantPrinter(val.get_child_at_index(0)) if type_kind == rustpp.TYPE_KIND_TUPLE_VARIANT: return RustStructPrinter(val, - omit_first_field = True, - omit_type_name = False, - is_tuple_like = True) + omit_first_field=True, + omit_type_name=False, + is_tuple_like=True) if type_kind == rustpp.TYPE_KIND_SINGLETON_ENUM: variant = get_field_at_index(gdb_val, 0) @@ -189,9 +190,9 @@ def rust_pretty_printer_lookup_function(gdb_val): return None -#=------------------------------------------------------------------------------ +# =------------------------------------------------------------------------------ # Pretty Printer Classes -#=------------------------------------------------------------------------------ +# =------------------------------------------------------------------------------ class RustEmptyPrinter(object): def __init__(self, val): self.__val = val @@ -355,6 +356,7 @@ def children_of_node(boxed_node, height, want_values): else: yield keys[i]['value']['value'] + class RustStdBTreeSetPrinter(object): def __init__(self, val): self.__val = val @@ -429,6 +431,7 @@ class RustOsStringPrinter(object): def display_hint(self): return "string" + class RustCStyleVariantPrinter(object): def __init__(self, val): assert val.type.get_dwarf_type_kind() == rustpp.DWARF_TYPE_CODE_ENUM diff --git a/src/etc/generate-deriving-span-tests.py b/src/etc/generate-deriving-span-tests.py index afa6bbdae4..c42f942c63 100755 --- a/src/etc/generate-deriving-span-tests.py +++ b/src/etc/generate-deriving-span-tests.py @@ -8,7 +8,8 @@ derives have spans that point to the fields, rather than the sample usage: src/etc/generate-deriving-span-tests.py """ -import os, stat +import os +import stat TEST_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), '../test/ui/derives/')) @@ -56,6 +57,7 @@ struct Struct( ENUM_TUPLE, ENUM_STRUCT, STRUCT_FIELDS, STRUCT_TUPLE = range(4) + def create_test_case(type, trait, super_traits, error_count): string = [ENUM_STRING, ENUM_STRUCT_VARIANT_STRING, STRUCT_STRING, STRUCT_TUPLE_STRING][type] all_traits = ','.join([trait] + super_traits) @@ -63,8 +65,9 @@ def create_test_case(type, trait, super_traits, error_count): error_deriving = '#[derive(%s)]' % super_traits if super_traits else '' errors = '\n'.join('//~%s ERROR' % ('^' * n) for n in range(error_count)) - code = string.format(traits = all_traits, errors = errors) - return TEMPLATE.format(error_deriving=error_deriving, code = code) + code = string.format(traits=all_traits, errors=errors) + return TEMPLATE.format(error_deriving=error_deriving, code=code) + def write_file(name, string): test_file = os.path.join(TEST_DIR, 'derives-span-%s.rs' % name) @@ -86,10 +89,10 @@ ALL = STRUCT | ENUM traits = { 'Default': (STRUCT, [], 1), - 'FromPrimitive': (0, [], 0), # only works for C-like enums + 'FromPrimitive': (0, [], 0), # only works for C-like enums - 'Decodable': (0, [], 0), # FIXME: quoting gives horrible spans - 'Encodable': (0, [], 0), # FIXME: quoting gives horrible spans + 'Decodable': (0, [], 0), # FIXME: quoting gives horrible spans + 'Encodable': (0, [], 0), # FIXME: quoting gives horrible spans } for (trait, supers, errs) in [('Clone', [], 1), diff --git a/src/etc/generate-keyword-tests.py b/src/etc/generate-keyword-tests.py index bc046a8f42..77c3d2758c 100755 --- a/src/etc/generate-keyword-tests.py +++ b/src/etc/generate-keyword-tests.py @@ -11,7 +11,6 @@ sample usage: src/etc/generate-keyword-tests.py as break import sys import os -import datetime import stat diff --git a/src/etc/htmldocck.py b/src/etc/htmldocck.py index e8be2b9b53..7789b24b62 100644 --- a/src/etc/htmldocck.py +++ b/src/etc/htmldocck.py @@ -131,6 +131,7 @@ try: except NameError: unichr = chr + class CustomHTMLParser(HTMLParser): """simplified HTML parser. @@ -169,21 +170,25 @@ class CustomHTMLParser(HTMLParser): HTMLParser.close(self) return self.__builder.close() + Command = namedtuple('Command', 'negated cmd args lineno context') + class FailedCheck(Exception): pass + class InvalidCheck(Exception): pass + def concat_multi_lines(f): """returns a generator out of the file object, which - removes `\\` then `\n` then a shared prefix with the previous line then optional whitespace; - keeps a line number (starting from 0) of the first line being concatenated.""" - lastline = None # set to the last line when the last line has a backslash + lastline = None # set to the last line when the last line has a backslash firstlineno = None catenated = '' for lineno, line in enumerate(f): @@ -208,6 +213,7 @@ def concat_multi_lines(f): if lastline is not None: print_err(lineno, line, 'Trailing backslash at the end of the file') + LINE_PATTERN = re.compile(r''' (?<=(?!?) (?P[A-Za-z]+(?:-[A-Za-z]+)*) @@ -252,7 +258,7 @@ def flatten(node): def normalize_xpath(path): if path.startswith('//'): - return '.' + path # avoid warnings + return '.' + path # avoid warnings elif path.startswith('.//'): return path else: @@ -316,7 +322,7 @@ class CachedFiles(object): def check_string(data, pat, regexp): if not pat: - return True # special case a presence testing + return True # special case a presence testing elif regexp: return re.search(pat, data, flags=re.UNICODE) is not None else: @@ -353,7 +359,7 @@ def check_tree_text(tree, path, pat, regexp): ret = check_string(value, pat, regexp) if ret: break - except Exception as e: + except Exception: print('Failed to get path "{}"'.format(path)) raise return ret @@ -363,6 +369,7 @@ def get_tree_count(tree, path): path = normalize_xpath(path) return len(tree.findall(path)) + def stderr(*args): if sys.version_info.major < 3: file = codecs.getwriter('utf-8')(sys.stderr) @@ -371,6 +378,7 @@ def stderr(*args): print(*args, file=file) + def print_err(lineno, context, err, message=None): global ERR_COUNT ERR_COUNT += 1 @@ -381,31 +389,33 @@ def print_err(lineno, context, err, message=None): if context: stderr("\t{}".format(context)) + ERR_COUNT = 0 + def check_command(c, cache): try: cerr = "" - if c.cmd == 'has' or c.cmd == 'matches': # string test + if c.cmd == 'has' or c.cmd == 'matches': # string test regexp = (c.cmd == 'matches') - if len(c.args) == 1 and not regexp: # @has = file existence + if len(c.args) == 1 and not regexp: # @has = file existence try: cache.get_file(c.args[0]) ret = True except FailedCheck as err: cerr = str(err) ret = False - elif len(c.args) == 2: # @has/matches = string test + elif len(c.args) == 2: # @has/matches = string test cerr = "`PATTERN` did not match" ret = check_string(cache.get_file(c.args[0]), c.args[1], regexp) - elif len(c.args) == 3: # @has/matches = XML tree test + elif len(c.args) == 3: # @has/matches = XML tree test cerr = "`XPATH PATTERN` did not match" tree = cache.get_tree(c.args[0]) pat, sep, attr = c.args[1].partition('/@') - if sep: # attribute + if sep: # attribute tree = cache.get_tree(c.args[0]) ret = check_tree_attr(tree, pat, attr, c.args[2], regexp) - else: # normalized text + else: # normalized text pat = c.args[1] if pat.endswith('/text()'): pat = pat[:-7] @@ -413,16 +423,16 @@ def check_command(c, cache): else: raise InvalidCheck('Invalid number of @{} arguments'.format(c.cmd)) - elif c.cmd == 'count': # count test - if len(c.args) == 3: # @count = count test + elif c.cmd == 'count': # count test + if len(c.args) == 3: # @count = count test expected = int(c.args[2]) found = get_tree_count(cache.get_tree(c.args[0]), c.args[1]) cerr = "Expected {} occurrences but found {}".format(expected, found) ret = expected == found else: raise InvalidCheck('Invalid number of @{} arguments'.format(c.cmd)) - elif c.cmd == 'has-dir': # has-dir test - if len(c.args) == 1: # @has-dir = has-dir test + elif c.cmd == 'has-dir': # has-dir test + if len(c.args) == 1: # @has-dir = has-dir test try: cache.get_dir(c.args[0]) ret = True @@ -448,11 +458,13 @@ def check_command(c, cache): except InvalidCheck as err: print_err(c.lineno, c.context, str(err)) + def check(target, commands): cache = CachedFiles(target) for c in commands: check_command(c, cache) + if __name__ == '__main__': if len(sys.argv) != 3: stderr('Usage: {}