1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//! `definitely::unreachable!()` is a macro for marking codepaths that are known
//! to be statically unreachable by the compiler's intraprocedural control flow
//! analysis, to ensure that they remain unreachable.
//!
//! This complements the standard library's
//! [`unsafe { core::hint::unreachable_unchecked() }`][unreachable_unchecked]
//! function and [`core::unreachable!()`] macro.
//!
//! [unreachable_unchecked]: core::hint::unreachable_unchecked
//!
//! | | safety | runtime behavior | binary size |
//! |---|---|---|---|
//! | core::hint::unreachable_unchecked | unsafe | undefined behavior if reached | zero |
//! | core::unreachable | safe | panic if reached | nonzero |
//! | definitely::unreachable | safe | impossible to reach | zero |
//!
//! # Example
//!
//! This use case has some complicated control flow involving retrying an API
//! call with a succession of different arguments in reaction to previous
//! observed failures. While there is a `loop` in the code, we would like to be
//! sure that every path through this loop body ends explicitly in a specific
//! intentional `return` or `break` or `continue` or panic. It should not be
//! possible for this to become an _implicit_ infinite loop during the course of
//! future refactorings.
//!
//! ```
//! # use std::io::{self, ErrorKind};
//! #
//! # fn do_thing(_: &str, _: Option<()>) -> io::Result<i32> { Ok(0) }
//! # fn default_value() -> i32 { 0 }
//! # fn alternate(_: &str) -> &str { "" }
//! #
//! # fn example() -> i32 {
//! # let b = ();
//! #
//! let mut retry_with_a = false;
//! let mut retry_with_b = false;
//! loop {
//! let mut arg = "...";
//! if retry_with_a {
//! arg = alternate(arg);
//! }
//! let thing = do_thing(arg, retry_with_b.then_some(b));
//! match thing {
//! Ok(outcome) => {
//! return outcome;
//! }
//! Err(err) if !retry_with_a && err.kind() == ErrorKind::NotFound => {
//! retry_with_a = true;
//! continue;
//! }
//! Err(err) if !retry_with_b => {
//! retry_with_b = true;
//! continue;
//! }
//! Err(err) => {
//! eprintln!("{}", err);
//! return default_value();
//! }
//! }
//!
//! definitely::unreachable!();
//! }
//! # }
//! ```