add modules & file writing

This commit is contained in:
notohh 2024-06-01 14:26:46 -04:00
parent 1cb0be1725
commit 5248d1de46
Signed by: notohh
GPG key ID: BD47506D475EE86D
3 changed files with 50 additions and 23 deletions

11
src/args.rs Normal file
View file

@ -0,0 +1,11 @@
use clap::Parser;
#[derive(Parser, Debug)]
pub struct Args {
#[arg(short)]
pub(crate) length: usize,
#[arg(short)]
pub write_to_file: bool,
#[arg(short, default_value_t = String::from("generated_pwd.txt"))]
pub file: String,
}

View file

@ -1,30 +1,27 @@
use args::Args;
use clap::Parser;
use rand::{distributions::Alphanumeric, Rng};
use core::panic;
use randomstring::RandomString;
use std::fs::File;
use std::io::{Error, Write};
#[derive(Parser, Debug)]
struct Args {
#[arg(short)]
length: usize,
}
mod args;
mod randomstring;
#[derive(Debug)]
struct RandomString;
impl RandomString {
fn generate_string(&self) -> String {
let args = Args::parse();
let s: String = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(args.length)
.map(char::from)
.collect();
s
}
}
fn main() {
fn main() -> Result<(), Error> {
let args = Args::parse();
let random_string = RandomString;
let string_output = random_string.generate_string();
println!("{}", string_output);
if args.write_to_file {
let f = &mut File::create(args.file);
let file = match f {
Ok(file) => file.write_all(string_output.as_bytes()),
Err(e) => panic!("cannot create file: {:?}", e),
};
} else {
println!("{}", string_output);
};
Ok(())
}

19
src/randomstring.rs Normal file
View file

@ -0,0 +1,19 @@
use clap::Parser;
use rand::{distributions::Alphanumeric, Rng};
use crate::Args;
#[derive(Debug)]
pub struct RandomString;
impl RandomString {
pub fn generate_string(&self) -> String {
let args = Args::parse();
let s: String = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(args.length)
.map(char::from)
.collect();
s
}
}