diff options
Diffstat (limited to 'docs')
-rw-r--r-- | docs/dev/style.md | 37 |
1 files changed, 36 insertions, 1 deletions
diff --git a/docs/dev/style.md b/docs/dev/style.md index 21330948b..389649398 100644 --- a/docs/dev/style.md +++ b/docs/dev/style.md | |||
@@ -280,6 +280,9 @@ Prefer `Default` even it has to be implemented manually. | |||
280 | 280 | ||
281 | **Rationale:** less typing in the common case, uniformity. | 281 | **Rationale:** less typing in the common case, uniformity. |
282 | 282 | ||
283 | Use `Vec::new` rather than `vec![]`. **Rationale:** uniformity, strength | ||
284 | reduction. | ||
285 | |||
283 | ## Functions Over Objects | 286 | ## Functions Over Objects |
284 | 287 | ||
285 | Avoid creating "doer" objects. | 288 | Avoid creating "doer" objects. |
@@ -418,12 +421,44 @@ fn frobnicate(s: &str) { | |||
418 | **Rationale:** reveals the costs. | 421 | **Rationale:** reveals the costs. |
419 | It is also more efficient when the caller already owns the allocation. | 422 | It is also more efficient when the caller already owns the allocation. |
420 | 423 | ||
421 | ## Collection types | 424 | ## Collection Types |
422 | 425 | ||
423 | Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`. | 426 | Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`. |
424 | 427 | ||
425 | **Rationale:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount. | 428 | **Rationale:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount. |
426 | 429 | ||
430 | ## Avoid Intermediate Collections | ||
431 | |||
432 | When writing a recursive function to compute a sets of things, use an accumulator parameter instead of returning a fresh collection. | ||
433 | Accumulator goes first in the list of arguments. | ||
434 | |||
435 | ```rust | ||
436 | // GOOD | ||
437 | pub fn reachable_nodes(node: Node) -> FxHashSet<Node> { | ||
438 | let mut res = FxHashSet::default(); | ||
439 | go(&mut res, node); | ||
440 | res | ||
441 | } | ||
442 | fn go(acc: &mut FxHashSet<Node>, node: Node) { | ||
443 | acc.insert(node); | ||
444 | for n in node.neighbors() { | ||
445 | go(acc, n); | ||
446 | } | ||
447 | } | ||
448 | |||
449 | // BAD | ||
450 | pub fn reachable_nodes(node: Node) -> FxHashSet<Node> { | ||
451 | let mut res = FxHashSet::default(); | ||
452 | res.insert(node); | ||
453 | for n in node.neighbors() { | ||
454 | res.extend(reachable_nodes(n)); | ||
455 | } | ||
456 | res | ||
457 | } | ||
458 | ``` | ||
459 | |||
460 | **Rational:** re-use allocations, accumulator style is more concise for complex cases. | ||
461 | |||
427 | # Style | 462 | # Style |
428 | 463 | ||
429 | ## Order of Imports | 464 | ## Order of Imports |