about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorJacob Kiesel <kieseljake@live.com>2022-09-15 20:50:28 -0600
committerJacob Kiesel <kieseljake@gmail.com>2022-10-01 13:58:41 -0600
commitb22118457245cdd074daaaaea950ec49397f8712 (patch)
treef89893cc5d5ed6da23eed321116308c321fae611 /src
parent31b17411a6cd5c4b36cde6ff008de1d3ec128ac4 (diff)
downloadrust-b22118457245cdd074daaaaea950ec49397f8712.tar.gz
rust-b22118457245cdd074daaaaea950ec49397f8712.zip
Implement manual_clamp lint
Diffstat (limited to 'src')
-rw-r--r--src/docs.rs1
-rw-r--r--src/docs/manual_clamp.txt46
2 files changed, 47 insertions, 0 deletions
diff --git a/src/docs.rs b/src/docs.rs
index 166be0618ff..39540e4b048 100644
--- a/src/docs.rs
+++ b/src/docs.rs
@@ -255,6 +255,7 @@ docs! {
     "manual_assert",
     "manual_async_fn",
     "manual_bits",
+    "manual_clamp",
     "manual_filter_map",
     "manual_find",
     "manual_find_map",
diff --git a/src/docs/manual_clamp.txt b/src/docs/manual_clamp.txt
new file mode 100644
index 00000000000..8993f6683ad
--- /dev/null
+++ b/src/docs/manual_clamp.txt
@@ -0,0 +1,46 @@
+### What it does
+Identifies good opportunities for a clamp function from std or core, and suggests using it.
+
+### Why is this bad?
+clamp is much shorter, easier to read, and doesn't use any control flow.
+
+### Known issue(s)
+If the clamped variable is NaN this suggestion will cause the code to propagate NaN
+rather than returning either `max` or `min`.
+
+`clamp` functions will panic if `max < min`, `max.is_nan()`, or `min.is_nan()`.
+Some may consider panicking in these situations to be desirable, but it also may
+introduce panicking where there wasn't any before.
+
+### Examples
+```
+if input > max {
+    max
+} else if input < min {
+    min
+} else {
+    input
+}
+```
+
+```
+input.max(min).min(max)
+```
+
+```
+match input {
+    x if x > max => max,
+    x if x < min => min,
+    x => x,
+}
+```
+
+```
+let mut x = input;
+if x < min { x = min; }
+if x > max { x = max; }
+```
+Use instead:
+```
+input.clamp(min, max)
+```
\ No newline at end of file