Skip to content

Instantly share code, notes, and snippets.

@monadplus
Last active October 28, 2022 14:41
Show Gist options
  • Save monadplus/fc2fefd19a2d18436a1dc2ebff0b5c15 to your computer and use it in GitHub Desktop.
Save monadplus/fc2fefd19a2d18436a1dc2ebff0b5c15 to your computer and use it in GitHub Desktop.
Rust: is palindrome
use std::{
error::Error,
fs::File,
io::{self, BufRead},
};
use clap::{ArgGroup, Parser};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
#[clap(group(
ArgGroup::new("vers")
.required(true)
.args(&["word", "file"]),
))]
struct Args {
#[arg(long, value_name = "STRING")]
word: Option<String>,
#[arg(short, long)]
file: Option<String>,
}
fn is_palindrome(s: &str) -> bool {
let s = s.as_bytes(); // Only for ASCII
let mut i = 0usize;
while i < s.len()/2 {
if s[i] != s[s.len() - 1 - i] {
return false;
}
i = i + 1;
}
return true;
}
fn main() -> Result<(), Box<dyn Error>> {
let print_is_palindrome = |word: String| {
if is_palindrome(&word[..]) {
println!("{word} is palindrome")
} else {
println!("{word} is not palindrome")
}
};
let Args { word, file } = Args::parse();
match (word, file) {
(Some(word), _) => {
print_is_palindrome(word);
Ok(())
}
(_, Some(file_name)) => {
let file = File::open(file_name)?;
for word in io::BufReader::new(file).lines() {
print_is_palindrome(word.unwrap());
}
Ok(())
}
_ => panic!("At least word or file should be defined by clap::group"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment