Skip to content

Commit 737533c

Browse files
bjorn3squell
authored andcommitted
Simplify reject_all
And also avoid memory allocations when there is no error to report.
1 parent d19cd0c commit 737533c

File tree

1 file changed

+16
-38
lines changed

1 file changed

+16
-38
lines changed

src/su/cli.rs

Lines changed: 16 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{borrow::Cow, mem, path::PathBuf};
1+
use std::{mem, path::PathBuf};
22

33
use crate::common::SudoString;
44

@@ -138,20 +138,20 @@ impl TryFrom<SuOptions> for SuRunOptions {
138138
}
139139

140140
fn reject_all(context: &str, opts: SuOptions) -> Result<(), String> {
141-
macro_rules! tuple {
142-
($expr:expr) => {
143-
(&$expr as &dyn IsAbsent, {
144-
let name = concat!("--", stringify!($expr));
145-
if name.contains('_') {
146-
Cow::Owned(name.replace('_', "-"))
147-
} else {
148-
Cow::Borrowed(name)
149-
}
150-
})
141+
macro_rules! ensure_options_absent {
142+
($($opt:ident,)*) => {
143+
let SuOptions {
144+
$($opt),*
145+
} = opts;
146+
147+
$(if !$opt.is_absent() {
148+
let name = concat!("--", stringify!($opt)).replace('_', "-");
149+
return Err(format!("{context} conflicts with {name}"));
150+
})*
151151
};
152152
}
153153

154-
let SuOptions {
154+
ensure_options_absent! {
155155
command,
156156
group,
157157
help,
@@ -163,37 +163,15 @@ fn reject_all(context: &str, opts: SuOptions) -> Result<(), String> {
163163
version,
164164
whitelist_environment,
165165
positional_args,
166-
} = opts;
167-
168-
let flags = [
169-
tuple!(command),
170-
tuple!(group),
171-
tuple!(help),
172-
tuple!(login),
173-
tuple!(preserve_environment),
174-
tuple!(pty),
175-
tuple!(shell),
176-
tuple!(supp_group),
177-
tuple!(version),
178-
tuple!(whitelist_environment),
179-
];
180-
for (value, name) in flags {
181-
ensure_is_absent(context, value, &name)?;
182-
}
166+
};
183167

184-
ensure_is_absent(context, &positional_args, "positional argument")?;
168+
if !positional_args.is_absent() {
169+
return Err(format!("{context} conflicts with positional argument"));
170+
}
185171

186172
Ok(())
187173
}
188174

189-
fn ensure_is_absent(context: &str, thing: &dyn IsAbsent, name: &str) -> Result<(), String> {
190-
if thing.is_absent() {
191-
Ok(())
192-
} else {
193-
Err(format!("{context} conflicts with {name}"))
194-
}
195-
}
196-
197175
trait IsAbsent {
198176
fn is_absent(&self) -> bool;
199177
}

0 commit comments

Comments
 (0)