feat(rand): #19 #21 add max rand and use number parser

This commit is contained in:
Christoph J. Scherr 2024-05-23 00:20:07 +02:00
parent 0923bf5247
commit 8fbc612f5a
2 changed files with 23 additions and 10 deletions

View File

@ -86,11 +86,16 @@ pub struct FormatOptions {
#[arg(short = 's', long)]
/// format to base64
base64: bool,
#[arg(short = 'r', long, default_value_t = 0)]
#[arg(short = 'r', long, default_value_t = 0, value_parser=numf_parser::<NumberType>)]
/// output random numbers
///
/// Add a user defined amount of cryptographically pseudorandom numbers to the number list.
rand: usize,
rand: NumberType,
#[arg(long, default_value_t = NumberType::MAX, value_parser=numf_parser::<NumberType>)]
/// max for the random numbers
///
/// Generated numbers will not be lower than this. Only has an effect with --rand set.
rand_max: NumberType,
#[arg(short = 'z', long)]
/// format to base32
base32: bool,
@ -190,14 +195,24 @@ impl FormatOptions {
}
/// get rand
pub fn rand(&self) -> usize {
pub fn rand(&self) -> NumberType {
self.rand
}
/// set amount of extra random numbers manually
pub fn set_rand(&mut self, rand: usize) {
pub fn set_rand(&mut self, rand: NumberType) {
self.rand = rand;
}
/// get highes allowed random value
pub fn rand_max(&self) -> NumberType {
self.rand_max
}
/// set highes allowed random value
pub fn set_rand_max(&mut self, rand_max: NumberType) {
self.rand_max = rand_max;
}
}
impl Default for FormatOptions {
@ -212,7 +227,8 @@ impl Default for FormatOptions {
base64: false,
dec: false,
numbers: vec![],
rand: 0
rand: 0,
rand_max: NumberType::MAX
}
}
}

View File

@ -10,7 +10,7 @@ use clap::{CommandFactory, Parser};
mod format;
use format::*;
use numf::format::{numf_parser, NumberType};
use numf::format::numf_parser;
fn main() -> anyhow::Result<()> {
// try to read from stdin first, appending the numbers we read to the FormatOptions
@ -53,10 +53,7 @@ fn main() -> anyhow::Result<()> {
use rand::prelude::*;
let mut rand = rand::rngs::OsRng;
for _i in 0..options.rand() {
let mut by: [u8; 16] = [0; 16];
rand.fill_bytes(&mut by);
let n: NumberType = libpt::bintols::join::array_to_unsigned(&by)?;
options.push_number(n);
options.push_number(rand.gen_range(0..options.rand_max()));
}
}