Fix some clippy lints

This commit is contained in:
Nathan Fisher 2023-01-03 19:47:00 -05:00
parent 829dad2c5f
commit 95b781ae9a
8 changed files with 71 additions and 57 deletions

View File

@ -1,5 +1,5 @@
use super::Cmd; use super::Cmd;
use clap::{Arg, ArgAction, Command, value_parser}; use clap::{value_parser, Arg, ArgAction, Command};
use data_encoding::BASE32; use data_encoding::BASE32;
use std::{ use std::{
fs, fs,
@ -61,20 +61,19 @@ impl Cmd for Base32 {
} }
fn run(&self, matches: Option<&clap::ArgMatches>) -> Result<(), Box<dyn std::error::Error>> { fn run(&self, matches: Option<&clap::ArgMatches>) -> Result<(), Box<dyn std::error::Error>> {
let matches = match matches { let Some(matches) = matches else {
Some(m) => m, return Err(io::Error::new(io::ErrorKind::Other, "No input").into());
None => return Err(io::Error::new(io::ErrorKind::Other, "No input").into()),
}; };
let files: Vec<_> = match matches.get_many::<String>("INPUT") { let files: Vec<_> = match matches.get_many::<String>("INPUT") {
Some(c) => c.map(|x| x.to_owned()).collect(), Some(c) => c.map(|x| x.clone()).collect(),
None => vec![String::from("-")], None => vec![String::from("-")],
}; };
let len = files.len(); let len = files.len();
for (index, file) in files.into_iter().enumerate() { for (index, file) in files.into_iter().enumerate() {
if { len > 1 || matches.get_flag("VERBOSE") } && !matches.get_flag("QUIET") { if { len > 1 || matches.get_flag("VERBOSE") } && !matches.get_flag("QUIET") {
match index { match index {
0 => println!("===> {} <===", file), 0 => println!("===> {file} <==="),
_ => println!("\n===> {} <===", file), _ => println!("\n===> {file} <==="),
}; };
} else if index > 0 { } else if index > 0 {
println!(); println!();
@ -111,14 +110,14 @@ fn decode_base32(mut contents: String, ignore: bool) {
let decoded = match BASE32.decode(contents.as_bytes()) { let decoded = match BASE32.decode(contents.as_bytes()) {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
eprintln!("base32: {}", e); eprintln!("base32: {e}");
process::exit(1); process::exit(1);
} }
}; };
let output = match String::from_utf8(decoded) { let output = match String::from_utf8(decoded) {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
eprintln!("base32: {}", e); eprintln!("base32: {e}");
process::exit(1); process::exit(1);
} }
}; };
@ -134,7 +133,7 @@ fn encode_base32(contents: &str, wrap: usize) {
.map(|c| c.iter().collect::<String>()) .map(|c| c.iter().collect::<String>())
.collect::<Vec<String>>(); .collect::<Vec<String>>();
for line in &encoded { for line in &encoded {
println!("{}", line); println!("{line}");
} }
} }
@ -144,15 +143,15 @@ fn get_contents(file: &str) -> String {
match io::stdin().read_to_string(&mut contents) { match io::stdin().read_to_string(&mut contents) {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
eprintln!("base32: {}", e); eprintln!("base32: {e}");
process::exit(1); process::exit(1);
} }
}; };
} else { } else {
contents = match fs::read_to_string(&file) { contents = match fs::read_to_string(file) {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
eprintln!("base32: {}", e); eprintln!("base32: {e}");
process::exit(1); process::exit(1);
} }
}; };

View File

@ -163,9 +163,7 @@ impl Cmd for Bootstrap {
} }
fn run(&self, matches: Option<&ArgMatches>) -> Result<(), Box<dyn Error>> { fn run(&self, matches: Option<&ArgMatches>) -> Result<(), Box<dyn Error>> {
let matches = if let Some(m) = matches { let Some(matches) = matches else {
m
} else {
return Err(io::Error::new(ErrorKind::Other, "No input").into()); return Err(io::Error::new(ErrorKind::Other, "No input").into());
}; };
if let Some(prefix) = matches.get_one::<String>("prefix") { if let Some(prefix) = matches.get_one::<String>("prefix") {

View File

@ -46,9 +46,9 @@ impl Cmd for Dirname {
path.to_string() path.to_string()
}; };
if matches.get_flag("zero") { if matches.get_flag("zero") {
print!("{}\0", path); print!("{path}\0");
} else { } else {
println!("{}", path); println!("{path}");
} }
}); });
} }
@ -60,4 +60,3 @@ impl Cmd for Dirname {
self.path self.path
} }
} }

View File

@ -1,6 +1,9 @@
use clap::{Arg, ArgMatches, Command, value_parser};
use crate::Cmd; use crate::Cmd;
use std::{error::Error, io::{self, BufRead}}; use clap::{value_parser, Arg, ArgMatches, Command};
use std::{
error::Error,
io::{self, BufRead},
};
#[derive(Debug)] #[derive(Debug)]
pub struct Factor { pub struct Factor {
@ -23,13 +26,13 @@ impl Cmd for Factor {
.about("factor numbers") .about("factor numbers")
.after_help( .after_help(
"Print the prime factors of each specified integer NUMBER. If none are\n\ "Print the prime factors of each specified integer NUMBER. If none are\n\
specified on the command line, read them from standard input." specified on the command line, read them from standard input.",
) )
.arg( .arg(
Arg::new("number") Arg::new("number")
.help("the numbers to factor") .help("the numbers to factor")
.num_args(0..) .num_args(0..)
.value_parser(value_parser!(u64)) .value_parser(value_parser!(u64)),
) )
} }
@ -38,15 +41,14 @@ impl Cmd for Factor {
match matches.get_many::<u64>("number") { match matches.get_many::<u64>("number") {
Some(numbers) => { Some(numbers) => {
numbers.for_each(|n| print_factors(*n)); numbers.for_each(|n| print_factors(*n));
}, }
None => { None => {
for line in io::stdin().lock().lines() { for line in io::stdin().lock().lines() {
for value in line.unwrap().split_whitespace() { for num in line?.split_whitespace() {
let num: u64 = value.parse()?; print_factors(num.parse()?);
print_factors(num); }
} }
} }
},
} }
} }
Ok(()) Ok(())
@ -57,30 +59,28 @@ impl Cmd for Factor {
} }
} }
fn is_prime(num: u64) -> bool { fn first_factor(num: u64) -> u64 {
match num { if crate::math::is_prime(num) {
0 | 1 => false, return num;
2 | 3 | 5 | 7 | 11 | 13 => true,
x if x % 2 == 0 => false,
_ => {
let mut x: u64 = 2;
while x < num / 2 {
if num % x == 0 {
return false;
} }
x += 1; for n in 2..=num {
} if num % n == 0 {
true return n;
} }
} }
num
} }
fn print_factors(num: u64) { fn print_factors(num: u64) {
print!("{num}:"); print!("{num}:");
for n in 2..=num / 2 { let mut n = num;
if num % n == 0 && is_prime(n) { loop {
print!(" {n}"); let f = first_factor(n);
print!(" {f}");
if f == n {
break;
} }
n /= f;
} }
println!(); println!();
} }

View File

@ -80,19 +80,17 @@ impl Cmd for Head {
if arg1.starts_with('-') && arg1.len() > 1 { if arg1.starts_with('-') && arg1.len() > 1 {
let lines: usize = arg1[1..].parse()?; let lines: usize = arg1[1..].parse()?;
let files: Vec<_> = if args.len() > idx + 1 { let files: Vec<_> = if args.len() > idx + 1 {
args[idx + 1..].iter().map(|x| x.as_str()).collect() args[idx + 1..].iter().map(String::as_str).collect()
} else { } else {
vec!["-"] vec!["-"]
}; };
for file in &files { for file in &files {
head(&file, lines, false, false); head(file, lines, false, false);
} }
return Ok(()); return Ok(());
} }
} }
let matches = if let Some(m) = matches { let Some(matches) = matches else {
m
} else {
return Err(io::Error::new(io::ErrorKind::Other, "No input").into()); return Err(io::Error::new(io::ErrorKind::Other, "No input").into());
}; };
if let Some(l) = matches.get_one("LINES") { if let Some(l) = matches.get_one("LINES") {

View File

@ -1,4 +1,6 @@
use super::{Cmd, BASE_32, BOOTSTRAP, DIRNAME, ECHO, FACTOR, FALSE, HEAD, HOSTNAME, NOLOGIN, SLEEP, TRUE}; use super::{
Cmd, BASE_32, BOOTSTRAP, DIRNAME, ECHO, FACTOR, FALSE, HEAD, HOSTNAME, NOLOGIN, SLEEP, TRUE,
};
use clap::Command; use clap::Command;
use std::{ use std::{
error::Error, error::Error,
@ -45,9 +47,7 @@ impl Cmd for Shitbox {
} }
fn run(&self, matches: Option<&clap::ArgMatches>) -> Result<(), Box<dyn Error>> { fn run(&self, matches: Option<&clap::ArgMatches>) -> Result<(), Box<dyn Error>> {
let matches = if let Some(m) = matches { let Some(matches) = matches else {
m
} else {
return Err(Box::new(io::Error::new(ErrorKind::Other, "No input"))); return Err(Box::new(io::Error::new(ErrorKind::Other, "No input")));
}; };
match matches.subcommand() { match matches.subcommand() {

View File

@ -3,8 +3,10 @@ use std::{env, error::Error, path::PathBuf, string::ToString};
pub mod cmd; pub mod cmd;
use cmd::{ use cmd::{
Cmd, Commands, BASE_32, BOOTSTRAP, DIRNAME, ECHO, FALSE, FACTOR, HEAD, HOSTNAME, NOLOGIN, SHITBOX, SLEEP, TRUE, Cmd, Commands, BASE_32, BOOTSTRAP, DIRNAME, ECHO, FACTOR, FALSE, HEAD, HOSTNAME, NOLOGIN,
SHITBOX, SLEEP, TRUE,
}; };
pub mod math;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum Path { pub enum Path {
@ -39,8 +41,8 @@ pub fn run() -> Result<(), Box<dyn Error>> {
cmd::COMMANDS cmd::COMMANDS
.set(Commands { .set(Commands {
items: vec![ items: vec![
&BASE_32, &BOOTSTRAP, &DIRNAME, &ECHO, &FALSE, &FACTOR, &HEAD, &HOSTNAME, &NOLOGIN, &TRUE, &SLEEP, &BASE_32, &BOOTSTRAP, &DIRNAME, &ECHO, &FALSE, &FACTOR, &HEAD, &HOSTNAME,
&SHITBOX, &NOLOGIN, &TRUE, &SLEEP, &SHITBOX,
], ],
}) })
.expect("Cannot register commands"); .expect("Cannot register commands");

18
src/math.rs Normal file
View File

@ -0,0 +1,18 @@
#[must_use]
pub fn is_prime(num: u64) -> bool {
match num {
0 | 1 => false,
2 | 3 | 5 | 7 | 11 | 13 => true,
x if x % 2 == 0 => false,
_ => {
let mut x: u64 = 2;
while x < num / 2 {
if num % x == 0 {
return false;
}
x += 1;
}
true
}
}
}