Skip to content

Commit

Permalink
Restructure Cookbook (rust-lang-nursery#404)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyGauge authored Jul 10, 2018
1 parent 601873e commit 97dabe5
Show file tree
Hide file tree
Showing 175 changed files with 6,550 additions and 6,692 deletions.
2 changes: 2 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ No worries if anything in these lists is unclear. Just submit the PR and ask awa
- [ ] commits are squashed into one and rebased to latest master
- [ ] PR contains correct "fixes #ISSUE_ID" clause to autoclose the issue on PR merge
- if issue does not exist consider creating it or remove the clause
- [ ] spell check runs without errors `./ci/spellchecker.sh`
- [ ] link check runs without errors `link-checker ./book`
- [ ] non rendered items are in sorted order (links, reference, identifiers, Cargo.toml)
- [ ] links to docs.rs have wildcard version `https://docs.rs/tar/*/tar/struct.Entry.html`
- [ ] example has standard [error handling](https://rust-lang-nursery.github.io/rust-cookbook/about.html#a-note-about-error-handling)
Expand Down
82 changes: 68 additions & 14 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,68 @@ To run the cookbook test suite:
cargo test
```

## Linters

The Rust Cookbook comes with link checking and spell checking linters that
run on the continuous integration server. These linters should be run locally
before submitting a pull request to ensure there are no dead links or spelling
errors made.

To install the link checker, review the documentation for [python] to install
python 3.6 and pip3. Installing link-checker once the dependencies are met
is done with pip3.

```
[sudo] pip3 install link-checker==0.1.0
```

Alternatively, set up the user install directory on your PATH variable and
install link-checker for your user

```
pip3 install -user link-checker==0.1.0
```

Checking the links of the book locally first requires the book to be built
with mdBook. From the root directory of the cookbook, the following commands
run the link checker.

```
mdbook build
link-checker ./book
```

The aspell binary provides spell checking. Apt packages provide installation
on Debian based operating systems.

```
[sudo] apt install aspell -y
```

To check the spelling of the Rust Cookbook locally, run the following command
from the root of the Cookbook.

```
./ci/spellchecker.sh
```

If the spell checker finds a misspelled word, you have the opportunity to
correct the spelling mistake with the number keys. If the spelling mistake
is erroneous, add the word to the dictionary located in `ci/dictionary.txt`.
Pressing `a` or `l` will not add the word to the custom dictionary.

[mdbook]: http://azerupi.github.io/mdBook/index.html
[python]: https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel
[skeptic]: https://github.com/brson/rust-skeptic


## Finding what to contribute

This project is intended to be simple to contribute to, and to always
have obvious next work items available. If at any time there is not
something obvious to contribute, that is a bug. Please ask for
assistance on the [libz blitz] thread, or email Brian Anderson
directly ([email protected]).
something obvious to contribute, that is a bug. Feel free to ask for
additional support at the
[Rust Ecosystem Working Group](https://gitter.im/rust-lang/WG-ecosystem).

The development process for the cookbook is presently oriented around
crates: we decide which crates to represent in the cookbook, then come
Expand Down Expand Up @@ -146,16 +198,18 @@ something a typical Rust user typically wants to do.
#### Description

Describe traits imported and the methods used. Think about what information
supports the use case and might not be obvious to someone new. Keep the
description to 1-4 sentences, avoiding explanations outside the scope of the
supports the use case and might not be obvious to someone new. Keep the
description to 1-4 sentences, avoiding explanations outside the scope of the
code sample.

Use third person narative of the code execution, taking the opportunity
to link to API documentation. Hyperlink all references to APIs, either
Use third person narrative of the code execution, taking the opportunity
to link to API documentation. Always use
[active voice](https://www.plainlanguage.gov/guidelines/conversational/use-active-voice/).
Hyperlink all references to APIs, either
on doc.rust-lang.org/std or docs.rs, and style them as `code`. Use
wildcard version specifiers for crate links.

Any requirements to execute the code that are not apparent, such as
Any requirements to execute the code that are not apparent, such as
passing environment flags, or configuring `Cargo.toml` should be added
after the code sample.

Expand All @@ -164,8 +218,8 @@ after the code sample.
> distribution, then sample from that distribution using
> [`Distribution::sample`] with help of a random-number
> generator [`rand::Rng`].
>
> The [distributions available are documented here][rand-distributions].
>
> The [distributions available are documented here][rand-distributions].
> An example using the [`Normal`] distribution is shown below.
[uniform distribution]: https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)
Expand All @@ -190,11 +244,11 @@ error handling correctly and propagate errors with `?` (not `try!`, `urwrap`, or
`expect`). If there is no need for error handling in the example, prefer `main()`.

Avoid glob imports (`*`), even for preludes, so that users can see what
traits are called. (Some crates might consider using glob imports for preludes
traits are called. (Some crates might consider using glob imports for preludes
best practice, making this awkward.)

Examples should be simple and obvious enough that an experienced dev
do not need comments.
do not need comments.

Examples should compile without warnings, clippy lint warnings, or panics.
The code should be formatted by rustfmt. Hide all error boilerplate and
Expand All @@ -206,9 +260,9 @@ explanation in the description.

> ```rust
> extern crate rand;
>
>
> use rand::distributions::{Normal, Distribution};
>
>
> fn main() {
> let mut rng = rand::thread_rng();
> let normal = Normal::new(2.0, 3.0);
Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ syslog = "4.0"

[build-dependencies]
skeptic = "0.13"
walkdir = "2.0"

[dev-dependencies]
skeptic = "0.13"
walkdir = "2.0"
5 changes: 3 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
extern crate skeptic;
extern crate walkdir;

use std::fs;
use walkdir::WalkDir;

fn main() {
let paths = fs::read_dir("./src/").unwrap()
let paths = WalkDir::new("./src/").into_iter()
// convert paths to Strings
.map(|p| p.unwrap().path().to_str().unwrap().to_string())
// only compile markdown files
Expand Down
6 changes: 6 additions & 0 deletions ci/dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ akshat
alisha
AlphaNumeric
ApiResponse
apis
APIs
Appender
appender
applicationx
args
ascii
ashley
Expand Down Expand Up @@ -280,6 +283,7 @@ SystemRandom
SystemTime
SystemTimeError
TcpListener
tcpip
TcpStream
TempDir
tempdir
Expand All @@ -297,6 +301,7 @@ tuple
Tuple
typesafe
unary
unix
unwinded
UpperHex
uptime
Expand All @@ -310,6 +315,7 @@ usize
VarError
versa
Versioning
versioning
VersionReq
vreq
WalkDir
Expand Down
56 changes: 49 additions & 7 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,53 @@

[Table of Contents](intro.md)
[About](about.md)

- [Basics](basics.md)
- [Encoding](encoding.md)
- [Algorithms](algorithms.md)
- [Generate Random Values](algorithms/randomness.md)
- [Command Line](cli.md)
- [Argument Parsing](cli/arguments.md)
- [Compression](compression.md)
- [Working with Tarballs](compression/tar.md)
- [Concurrency](concurrency.md)
- [Networking](net.md)
- [Application development](app.md)
- [Logging](logging.md)
- [Build Time Tooling](build_tools.md)
- [Explicit Threads](concurrency/threads.md)
- [Data Parallelism](concurrency/parallel.md)
- [Cryptography](cryptography.md)
- [Hashing](cryptography/hashing.md)
- [Encryption](cryptography/encryption.md)
- [Data Structures](data_structures.md)
- [Bitfield](data_structures/bitfield.md)
- [Date and Time](datetime.md)
- [Duration and Calculation](datetime/duration.md)
- [Parsing and Displaying](datetime/parse.md)
- [Development Tools](development_tools.md)
- [Debugging](development_tools/debugging.md)
- [Log Messages](development_tools/debugging/log.md)
- [Configure Logging](development_tools/debugging/config_log.md)
- [Versioning](development_tools/versioning.md)
- [Build Time Tooling](development_tools/build_tools.md)
- [Encoding](encoding.md)
- [Character Sets](encoding/strings.md)
- [CSV processing](encoding/csv.md)
- [Structured Data](encoding/complex.md)
- [Error Handling](errors.md)
- [Handle Error Variants](errors/handle.md)
- [File System](file.md)
- [Read & Write](file/read-write.md)
- [Directory Traversal](file/dir.md)
- [Hardware Support](hardware.md)
- [Processor](hardware/processor.md)
- [Memory Management](mem.md)
- [Global Static](mem/global_static.md)
- [Network](net.md)
- [Server](net/server.md)
- [Operating System](os.md)
- [External Command](os/external.md)
- [Text Processing](text.md)
- [Regular Expressions](text/regex.md)
- [Web Programming](web.md)
- [Extracting Links](web/scraping.md)
- [URL](web/url.md)
- [Media Types](web/mime.md)
- [Clients](web/clients.md)
- [Making Requests](web/clients/requests.md)
- [Calling a Web API](web/clients/apis.md)
- [Downloads](web/clients/download.md)
19 changes: 19 additions & 0 deletions src/algorithms.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Algorithms

| Recipe | Crates | Categories |
|--------|--------|------------|
| [Generate random numbers][ex-rand] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Generate random numbers within a range][ex-rand-range] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Generate random numbers with given distribution][ex-rand-dist] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Generate random values of a custom type][ex-rand-custom] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Create random passwords from a set of alphanumeric characters][ex-rand-passwd] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |
| [Create random passwords from a set of user-defined characters][ex-rand-choose] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |

[ex-rand]: algorithms/randomness.html#generate-random-numbers
[ex-rand-range]: algorithms/randomness.html#generate-random-numbers-within-a-range
[ex-rand-dist]: algorithms/randomness.html#generate-random-numbers-with-given-distribution
[ex-rand-custom]: algorithms/randomness.html#generate-random-values-of-a-custom-type
[ex-rand-passwd]: algorithms/randomness.html#create-random-passwords-from-a-set-of-alphanumeric-characters
[ex-rand-choose]: algorithms/randomness.html#create-random-passwords-from-a-set-of-user-defined-characters

{{#include links.md}}
15 changes: 15 additions & 0 deletions src/algorithms/randomness.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Generate Random Values

{{#include randomness/rand.md}}

{{#include randomness/rand-range.md}}

{{#include randomness/rand-dist.md}}

{{#include randomness/rand-custom.md}}

{{#include randomness/rand-passwd.md}}

{{#include randomness/rand-choose.md}}

{{#include ../links.md}}
26 changes: 26 additions & 0 deletions src/algorithms/randomness/rand-choose.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
## Create random passwords from a set of user-defined characters

[![rand-badge]][rand] [![cat-os-badge]][cat-os]

Randomly generates a string of given length ASCII characters with custom user-defined bytestring, with [`choose`].

```rust
extern crate rand;

use rand::{thread_rng, Rng};

fn main() {
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789)(*&^%$#@!~";

let mut rng = thread_rng();
let password: Option<String> = (0..30)
.map(|_| Some(*rng.choose(CHARSET)? as char))
.collect();

println!("{:?}", password);
}
```

[`choose`]: https://docs.rs/rand/*/rand/trait.Rng.html#method.choose
40 changes: 40 additions & 0 deletions src/algorithms/randomness/rand-custom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
## Generate random values of a custom type

[![rand-badge]][rand] [![cat-science-badge]][cat-science]

Randomly generates a tuple `(i32, bool, f64)` and variable of user defined type `Point`.
Implements the [`Distribution`] trait on type Point for [`Standard`] in order to allow random generation.

```rust
extern crate rand;

use rand::Rng;
use rand::distributions::{Distribution, Standard};

#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}

impl Distribution<Point> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Point {
let (rand_x, rand_y) = rng.gen();
Point {
x: rand_x,
y: rand_y,
}
}
}

fn main() {
let mut rng = rand::thread_rng();
let rand_tuple = rng.gen::<(i32, bool, f64)>();
let rand_point: Point = rng.gen();
println!("Random tuple: {:?}", rand_tuple);
println!("Random Point: {:?}", rand_point);
}
```

[`Distribution`]: https://docs.rs/rand/*/rand/distributions/trait.Distribution.html
[`Standard`]: https://docs.rs/rand/*/rand/distributions/struct.Standard.html
32 changes: 32 additions & 0 deletions src/algorithms/randomness/rand-dist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
## Generate random numbers with given distribution

[![rand-badge]][rand] [![cat-science-badge]][cat-science]

By default, random numbers have [uniform distribution].
To generate numbers with other distributions you instantiate a
distribution, then sample from that distribution using
[`IndependentSample::ind_sample`] with help of a random-number
generator [`rand::Rng`].

The [distributions available are documented here][rand-distributions]. An example using the
[`Normal`] distribution is shown below.

```rust
extern crate rand;

use rand::distributions::{Normal, Distribution};

fn main() {
let mut rng = rand::thread_rng();
let normal = Normal::new(2.0, 3.0);
let v = normal.sample(&mut rng);
println!("{} is from a N(2, 9) distribution", v)
}
```

[`Distribution::sample`]: https://docs.rs/rand/*/rand/distributions/trait.Distribution.html#tymethod.sample
[`Normal`]: https://docs.rs/rand/*/rand/distributions/normal/struct.Normal.html
[`rand::Rng`]: https://docs.rs/rand/*/rand/trait.Rng.html
[rand-distributions]: https://docs.rs/rand/*/rand/distributions/index.html

[uniform distribution]: https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)
Loading

0 comments on commit 97dabe5

Please sign in to comment.