Skip to content

Commit b114e0a

Browse files
committed
nice: Refactor clamp
1 parent 9959a11 commit b114e0a

File tree

2 files changed

+7
-17
lines changed

2 files changed

+7
-17
lines changed

src/uu/nice/src/nice.rs

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use clap::{Arg, ArgAction, Command};
99
use libc::PRIO_PROCESS;
1010
use std::ffi::OsString;
1111
use std::io::{Error, ErrorKind, Write};
12+
use std::num::IntErrorKind;
1213
use std::os::unix::process::CommandExt;
1314
use std::process;
1415

@@ -126,28 +127,16 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
126127
}
127128
match nstr.parse::<i32>() {
128129
Ok(num) => num,
129-
Err(e) => {
130-
// clamp huge values
131-
let trimmed = nstr.trim();
132-
let mut chars = trimmed.chars();
133-
let first = chars.next();
134-
let is_valid_number = (first.is_some_and(|c| c.is_ascii_digit())
135-
|| first == Some('-')
136-
|| first == Some('+'))
137-
&& chars.all(|c| c.is_ascii_digit());
138-
if is_valid_number {
139-
if first == Some('-') {
140-
i32::MIN
141-
} else {
142-
i32::MAX
143-
}
144-
} else {
130+
Err(e) => match e.kind() {
131+
IntErrorKind::PosOverflow => i32::MAX,
132+
IntErrorKind::NegOverflow => i32::MIN,
133+
_ => {
145134
return Err(USimpleError::new(
146135
125,
147136
translate!("nice-error-invalid-number", "value" => nstr.clone(), "error" => e),
148137
));
149138
}
150-
}
139+
},
151140
}
152141
}
153142
None => {

tests/by-util/test_nice.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ fn test_nice_huge_negative() {
108108
new_ucmd!().args(&["-n", "-9999999999", "true"]).succeeds(); // permission denied
109109
}
110110

111+
#[test]
111112
fn test_sign_middle() {
112113
new_ucmd!().args(&["-n", "-2+4", "true"]).fails();
113114
}

0 commit comments

Comments
 (0)