diff --git a/.gitignore b/.gitignore index f5064dd..c744ab9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ pkg/*.pkg.tar.zst pkg/*.tar.gz pkg/pkg/ pkg/src/ +result/ +flake.lock diff --git a/Cargo.lock b/Cargo.lock index 141615e..0f96371 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -144,7 +144,7 @@ dependencies = [ [[package]] name = "dolltool" -version = "1.3.0" +version = "1.4.0" dependencies = [ "clap", "num-bigint", diff --git a/README.md b/README.md index 27392cd..3b0478c 100644 --- a/README.md +++ b/README.md @@ -75,11 +75,19 @@ hello world :3 Generates random codes based on a user-defined pattern: -- `n`: Number (0-9) -- `l`: Letter (a-z) -- `L`: Uppercase Letter (A-Z) -- `a`: Alphanumeric (0-9, a-z) -- `A`: Uppercase Alphanumeric (0-9, a-z) +- `n`: Digit (0-9) +- `l`: Letter Lowercase (a-z) +- `L`: Letter Uppercase (A-Z) +- `m`: Letter Mixed (a-z, A-Z) +- `a`: Alphanumeric Lowercase (0-9, a-z) +- `A`: Alphanumeric Uppercase (0-9, A-Z) +- `x`: Alphanumeric Mixed (0-9, a-z, A-Z) +- `b`: Binary Digit (0-1) +- `o`: Octal Digit (0-7) +- `h`: Hex Lowercase (0-f) +- `H`: Hex Uppercase (0-F) +- `X`: Hex Mixed (0-9, a-f, A-F) +- `*`: any other character is used literally ```bash $ dolltool -g "nn-lll" -c 3 diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..96520ea --- /dev/null +++ b/flake.nix @@ -0,0 +1,73 @@ +{ + description = "A simple dollcode encoder, decoder, and generator inside your terminal :3"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + crane.url = "github:ipetkov/crane"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, crane, flake-utils }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = import nixpkgs { inherit system; }; + + craneLib = crane.mkLib pkgs; + + # Common build inputs / env shared across derivations. + # crane's default cargo source filter drops LICENSE, but main.rs does + # `include_str!("../LICENSE")`, so we keep it alongside cargo sources. + commonArgs = { + src = pkgs.lib.cleanSourceWith { + src = ./.; + filter = path: type: + craneLib.filterCargoSources path type + || baseNameOf path == "LICENSE"; + }; + strictDeps = true; + }; + + # Build *just* the dependencies so they can be cached and reused + # across source changes. (Edition 2024 needs Rust >= 1.85, which + # nixpkgs-unstable ships by default.) + cargoArtifacts = craneLib.buildDepsOnly commonArgs; + + dolltool = craneLib.buildPackage (commonArgs // { + inherit cargoArtifacts; + doCheck = true; + }); + in + { + packages = { + default = dolltool; + inherit dolltool; + }; + + apps.default = flake-utils.lib.mkApp { + drv = dolltool; + name = "dolltool"; + }; + + devShells.default = pkgs.mkShell { + inputsFrom = [ dolltool ]; + packages = with pkgs; [ + rustc + cargo + cargo-edit + rustfmt + clippy + ]; + }; + + checks = { + inherit dolltool; + clippy = craneLib.cargoClippy (commonArgs // { + inherit cargoArtifacts; + cargoClippyExtraArgs = "--all-targets -- --deny warnings"; + }); + fmt = craneLib.cargoFmt (commonArgs // { + inherit cargoArtifacts; + }); + }; + }); +} \ No newline at end of file diff --git a/pkg/PKGBUILD b/pkg/PKGBUILD index 0f2faf6..6c906a9 100644 --- a/pkg/PKGBUILD +++ b/pkg/PKGBUILD @@ -1,6 +1,6 @@ # Maintainer: jaiden brooke pkgname=dolltool -pkgver=1.3.0 +pkgver=1.4.0 pkgrel=1 pkgdesc="A simple dollcode encoder, decoder, and generator inside your terminal" url=https://git.gay/ika4422/dolltool @@ -9,7 +9,7 @@ license=('GPL-3.0-or-later') depends=('glibc' 'libgcc') makedepends=('rust' 'cargo') source=("$pkgname-$pkgver.tar.gz::https://git.gay/ika4422/dolltool/archive/v$pkgver.tar.gz") -sha256sums=('195c60071637980cb9163bfd8c54b00ebb4dde5306fdfc977ea0eb855679fac5') +sha256sums=('d536e6b3d93ce85cc48780565f1ac461a424bf0deff64fc95d474af5bdee29ec') build() { cd "$srcdir/../.." diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 0000000..771b9b1 --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,112 @@ +use std::process; + +use num_bigint::BigUint; +use num_traits::ToPrimitive; + +use crate::{ + dollcode::{from_dollcode, to_dollcode}, + pattern_gen::generate_from_pattern, +}; + +pub fn run_generate(pattern: &str, count: usize, base: u32, no_doll: bool, text: bool) { + let mut generated_count = 0; + + while generated_count < count { + let generated = generate_from_pattern(pattern, base); + + if no_doll { + println!("{}", generated); + generated_count += 1; + continue; + } + + let num = if text { + None + } else { + BigUint::parse_bytes(generated.as_bytes(), base) + }; + + match num { + Some(num) => match to_dollcode(num) { + Ok(code) => { + println!("{} :: {}", generated, code); + generated_count += 1; + } + Err(_) => continue, + }, + None => { + let doll: Vec = generated + .chars() + .map(|c| to_dollcode(BigUint::from(c as u64)).unwrap()) + .collect(); + + println!("{} :: {}", generated, doll.join(" ")); + generated_count += 1; + } + } + } +} + +pub fn run_encode(input: &str, base: u32, text: bool) { + let encode_as_text = text || BigUint::parse_bytes(input.as_bytes(), base).is_none(); + + if encode_as_text { + let result: Vec = input + .chars() + .map(|c| to_dollcode(BigUint::from(c as u64)).unwrap()) + .collect(); + println!("{}", result.join(" ")); + } else { + let num = BigUint::parse_bytes(input.as_bytes(), base).unwrap(); + + match to_dollcode(num) { + Ok(code) => println!("{}", code), + Err(e) => { + eprintln!("Error: {}", e); + process::exit(1); + } + } + } +} + +pub fn run_decode(input: &str, base: u32, text: bool, all_bases: bool) { + let decode_as_text = text || input.split_whitespace().count() > 1; + + if decode_as_text { + let mut decoded_chars = String::new(); + + for part in input.split_whitespace() { + match from_dollcode(part) { + Ok(val) => { + if let Some(u) = val.to_u32() { + decoded_chars.push(char::from_u32(u).unwrap_or('?')); + } else { + decoded_chars.push('?'); + } + } + Err(e) => { + eprintln!("Error: {}", e); + process::exit(1); + } + } + } + println!("{}", decoded_chars); + } else { + match from_dollcode(input) { + Ok(val) => { + if all_bases { + println!("bin :: {}", val.to_str_radix(2)); + println!("oct :: {}", val.to_str_radix(8)); + println!("dec :: {}", val.to_str_radix(10)); + println!("hex :: {}", val.to_str_radix(16)); + } else { + println!("{}", val.to_str_radix(base)); + } + } + Err(e) => { + eprintln!("Error: {}", e); + process::exit(1); + } + } + } +} diff --git a/src/main.rs b/src/main.rs index 80143b4..862230d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,66 +15,23 @@ * along with this program. If not, see . */ +mod commands; mod dollcode; +mod models; mod pattern_gen; use std::process; use clap::Parser; -use num_bigint::BigUint; -use num_traits::ToPrimitive; -use crate::{ - dollcode::{from_dollcode, to_dollcode}, - pattern_gen::generate_from_pattern, -}; - -#[derive(Parser, Debug)] -#[command(author, version, about)] -struct Args { - #[arg(short, long)] - /// Encodes the following integer or text into dollcode - encode: Option, - - #[arg(short, long)] - /// Decodes the following dollcode into an integer or text - decode: Option, - - #[arg(short, long)] - /// Generates codes from a user-defined pattern (see --tokens for token list) - generate: Option, - - #[arg(short, long, default_value_t = 1)] - /// Specifies how many codes to generate - count: usize, - - #[arg(short, long, default_value_t = 10)] - /// Input/output base for integers (2, 8, 10, 16) - base: u32, - - #[arg(long, default_value_t = false)] - /// Will generate codes without encoding it into dollcode - no_doll: bool, - - #[arg(short, long, default_value_t = false)] - /// Specifies the encoding/decoding method as text, instead of an integer - text: bool, - - #[arg(long, default_value_t = false)] - /// List all available pattern tokens - tokens: bool, - - #[arg(long)] - /// Display the license for dolltool - license: bool, -} +use crate::models::Args; fn main() { let args = Args::parse(); if args.license { println!("{}", include_str!("../LICENSE")); - process::exit(1); + process::exit(0); } if args.tokens { @@ -83,83 +40,16 @@ fn main() { } if let Some(pattern) = args.generate { - for _ in 0..args.count { - let generated = generate_from_pattern(&pattern); - - if args.no_doll { - println!("{}", generated); - } else { - let as_num = if args.text { - None - } else { - BigUint::parse_bytes(generated.as_bytes(), args.base) - }; - - match as_num { - Some(num) => { - println!("{} :: {}", generated, to_dollcode(num).unwrap()); - } - None => { - let doll: Vec = generated - .chars() - .map(|c| to_dollcode(BigUint::from(c as u64)).unwrap()) - .collect(); - println!("{} :: {}", generated, doll.join(" ")); - } - } - } - } + commands::run_generate( + &pattern, + args.count, + args.base.radix(), + args.no_doll, + args.text, + ); } else if let Some(input) = args.encode { - let encode_as_text = - args.text || BigUint::parse_bytes(input.as_bytes(), args.base).is_none(); - - if encode_as_text { - let result: Vec = input - .chars() - .map(|c| to_dollcode(BigUint::from(c as u64)).unwrap()) - .collect(); - println!("{}", result.join(" ")); - } else { - let num = BigUint::parse_bytes(input.as_bytes(), args.base).unwrap(); - - match to_dollcode(num) { - Ok(code) => println!("{}", code), - Err(e) => { - eprintln!("Error: {}", e); - process::exit(1); - } - } - } + commands::run_encode(&input, args.base.radix(), args.text); } else if let Some(input) = args.decode { - let decode_as_text = args.text || input.split_whitespace().count() > 1; - - if decode_as_text { - let mut decoded_chars = String::new(); - - for part in input.split_whitespace() { - match from_dollcode(part) { - Ok(val) => { - if let Some(u) = val.to_u32() { - decoded_chars.push(char::from_u32(u).unwrap_or('?')); - } else { - decoded_chars.push('?'); - } - } - Err(e) => { - eprintln!("Error: {}", e); - process::exit(1); - } - } - } - println!("{}", decoded_chars); - } else { - match from_dollcode(&input) { - Ok(val) => println!("{}", val.to_str_radix(args.base)), - Err(e) => { - eprintln!("Error: {}", e); - process::exit(1); - } - } - } + commands::run_decode(&input, args.base.radix(), args.text, args.all_bases); } } diff --git a/src/models.rs b/src/models.rs new file mode 100644 index 0000000..e117baf --- /dev/null +++ b/src/models.rs @@ -0,0 +1,115 @@ +use clap::Parser; + +#[derive(Parser, Debug)] +#[command(author, version, about)] +pub struct Args { + #[arg(short, long, value_name = "INPUT")] + /// Encodes the following integer or text into dollcode + pub encode: Option, + + #[arg(short, long, value_name = "DOLLCODE")] + /// Decodes the following dollcode into an integer or text + pub decode: Option, + + #[arg(short, long, value_name = "PATTERN")] + /// Generates codes from a user-defined pattern (see --tokens for token list) + pub generate: Option, + + #[arg(short, long, default_value_t = 1, value_name = "N")] + /// Specifies how many codes to generate + pub count: usize, + + #[arg(short, long, default_value_t = Base(10))] + /// Input/output base for integers (2-36, or bin/oct/dec/hex/..) + pub base: Base, + + #[arg(long, default_value_t = false)] + /// Output result in binary, octal, decimal and hex + pub all_bases: bool, + + #[arg(long, default_value_t = false)] + /// Will generate codes without encoding it into dollcode + pub no_doll: bool, + + #[arg(short, long, default_value_t = false)] + /// Specifies the encoding/decoding method as text, instead of an integer + pub text: bool, + + #[arg(long, default_value_t = false)] + /// List all available pattern tokens + pub tokens: bool, + + #[arg(long)] + /// Display the license for dolltool + pub license: bool, +} + +#[derive(Debug, Clone, Copy)] +pub struct Base(u32); + +impl Base { + pub fn radix(self) -> u32 { + self.0 + } +} + +impl std::str::FromStr for Base { + type Err = String; + + fn from_str(s: &str) -> Result { + // c'tu inutile? ouais + // chu-tu une grosse nerd? ouais aussi + let radix = match s { + "bin" | "binary" => 2, + "ter" | "ternary" | "trinary" => 3, + "quat" | "quaternary" => 4, + "quin" | "quinary" => 5, + "sen" | "senary" => 6, + "sep" | "septenary" => 7, + "oct" | "octal" => 8, + "non" | "nonary" => 9, + "dec" | "denary" | "decimal" => 10, + "und" | "undecimal" => 11, + "duo" | "duodecimal" | "dozenal" => 12, + "tridecimal" => 13, + "tetradecimal" => 14, + "pentadecimal" => 15, + "hex" | "hexadecimal" => 16, + "heptadecimal" => 17, + "octodecimal" => 18, + "nonadecimal" | "enneadecimal" => 19, + "vig" | "vigesimal" => 20, + "unvigesimal" => 21, + "duovigesimal" => 22, + "trivigesimal" => 23, + "tetravigesimal" => 24, + "pentavigesimal" => 25, + "hexavigesimal" => 26, + "heptavigesimal" => 27, + "octovigesimal" => 28, + "nonavigesimal" => 29, + "trigesimal" => 30, + "untrigesimal" => 31, + "dtg" | "duotrigesimal" => 32, + "tritrigesimal" => 33, + "tetratrigesimal" => 34, + "pentatrigesimal" => 35, + "htg" | "hexatrigesimal" => 36, + _ => s + .parse::() + .map_err(|_| format!("'{}' is not a valid base", s))?, + }; + + if (2..=36).contains(&radix) { + Ok(Base(radix)) + } else { + Err(format!("base must be between 2 and 36, got {}", radix)) + } + } +} + +impl std::fmt::Display for Base { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/src/pattern_gen.rs b/src/pattern_gen.rs index efe42d3..00cc66e 100644 --- a/src/pattern_gen.rs +++ b/src/pattern_gen.rs @@ -1,63 +1,157 @@ use rand::RngExt; -const DIGITS: &[u8] = b"0123456789"; -const LETTERS_LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; -const LETTERS_UPPER: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; -const LETTERS_MIXED: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; -const ALNUM_LOWER: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz"; -const ALNUM_UPPER: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; -const ALNUM_MIXED: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; -const DIGITS_BINARY: &[u8] = b"01"; -const DIGITS_OCTAL: &[u8] = b"01234567"; -const DIGITS_HEX_LOWER: &[u8] = b"0123456789abcdef"; -const DIGITS_HEX_UPPER: &[u8] = b"0123456789ABCDEF"; -const DIGITS_HEX_MIXED: &[u8] = b"0123456789abcdefABCDEF"; - pub const TOKEN_HELP: &str = "\ -Pattern Tokens: - n digit (0-9) - l letter lower (a-z) - L letter upper (A-Z) - m letter mixed (a-z, A-Z) - a alnum lower (0-9, a-z) - A alnum upper (0-9, A-Z) - x alnum mixed (0-9, a-z, A-Z) - b binary digit (0-1) - o octal digit (0-7) - h hex lower (0-f) - H hex upper (0-F) - X hex mixed (0-9, a-f, A-F) - * any other character is used literally"; +Cased Tokens: + l[^~] letter (a-z / A-Z / both) + a[^~] alphanumeric (0-9; a-z / A-Z / both) + h[^~] hex digit (0-9; a-f / A-F / both) + r[^~] radix digit (0 to base-1, depends on --base) + +Fixed Tokens: + n / d digit (0-9) + b binary (0-1) + o octal (0-7) + +Repition: + t{N} repeat token t exactly N times (e.g. a{4}, h^{8}) + +* any other character is taken literally"; + +const DIGITS: &[u8] = b"0123456789"; +const LETTERS: &[u8] = b"abcdefghijklmnopqrstuvwxyz"; +const ALNUM: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz"; +const BINARY: &[u8] = b"01"; +const OCTAL: &[u8] = b"01234567"; +const HEX: &[u8] = b"0123456789abcdef"; + +#[derive(Debug, Clone, Copy, PartialEq)] +enum Case { + Lower, + Upper, + Mixed, +} + +#[derive(Debug, Clone, Copy)] +enum Token { + Digit, + Letter(Case), + Alnum(Case), + Binary, + Octal, + Hex(Case), + Radix(Case), + Literal(char), +} + +#[derive(Debug, Clone)] +struct PatternToken { + token: Token, + count: usize, +} + +pub fn generate_from_pattern(pattern: &str, base: u32) -> String { + let mut rng = rand::rng(); + let tokens = parse_pattern(pattern); + let mut output = String::with_capacity(tokens.iter().map(|t| t.count).sum()); + let radix_pool = &ALNUM[..base as usize]; + + for pt in tokens { + for _ in 0..pt.count { + let ch = match pt.token { + Token::Digit => pick(&mut rng, DIGITS), + Token::Binary => pick(&mut rng, BINARY), + Token::Octal => pick(&mut rng, OCTAL), + Token::Letter(case) => pick_cased(&mut rng, LETTERS, case), + Token::Alnum(case) => pick_cased(&mut rng, ALNUM, case), + Token::Hex(case) => pick_cased(&mut rng, HEX, case), + Token::Radix(case) => pick_cased(&mut rng, radix_pool, case), + Token::Literal(c) => c, + }; + output.push(ch); + } + } + output +} fn pick(rng: &mut impl rand::Rng, pool: &[u8]) -> char { pool[rng.random_range(0..pool.len())] as char } -pub fn generate_from_pattern(pattern: &str) -> String { - let mut rng = rand::rng(); - let mut output = String::with_capacity(pattern.len()); +fn pick_cased(rng: &mut impl rand::Rng, pool: &[u8], case: Case) -> char { + let ch = pick(rng, pool); - for c in pattern.chars() { - let pool = match c { - 'n' => Some(DIGITS), - 'l' => Some(LETTERS_LOWER), - 'L' => Some(LETTERS_UPPER), - 'm' => Some(LETTERS_MIXED), - 'a' => Some(ALNUM_LOWER), - 'A' => Some(ALNUM_UPPER), - 'x' => Some(ALNUM_MIXED), - 'b' => Some(DIGITS_BINARY), - 'o' => Some(DIGITS_OCTAL), - 'h' => Some(DIGITS_HEX_LOWER), - 'H' => Some(DIGITS_HEX_UPPER), - 'X' => Some(DIGITS_HEX_MIXED), - _ => None, + match case { + Case::Lower => ch, + Case::Upper => ch.to_ascii_uppercase(), + Case::Mixed => { + if rng.random::() { + ch.to_ascii_uppercase() + } else { + ch + } + } + } +} + +fn parse_case(chars: &mut std::iter::Peekable>) -> Case { + match chars.peek() { + Some(&'^') => { + chars.next(); + Case::Upper + } + Some(&'~') => { + chars.next(); + Case::Mixed + } + _ => Case::Lower, + } +} + +fn parse_pattern(pattern: &str) -> Vec { + let mut tokens = Vec::new(); + let mut chars = pattern.chars().peekable(); + + while let Some(c) = chars.next() { + let case = if matches!(c, 'l' | 'a' | 'h' | 'r') { + parse_case(&mut chars) + } else { + Case::Lower }; - output.push(match pool { - Some(p) => pick(&mut rng, p), - None => c, - }); + let (count, spill) = if chars.peek() == Some(&'{') { + chars.next(); + let inner: String = chars.by_ref().take_while(|&x| x != '}').collect(); + + match inner.parse::() { + Ok(n) if n > 0 => (n, None), + _ => (1, Some(inner)), + } + } else { + (1, None) + }; + + let token = match c { + 'n' | 'd' => Token::Digit, + 'b' => Token::Binary, + 'o' => Token::Octal, + 'l' => Token::Letter(case), + 'a' => Token::Alnum(case), + 'h' => Token::Hex(case), + 'r' => Token::Radix(case), + _ => Token::Literal(c), + }; + + tokens.push(PatternToken { token, count }); + + if let Some(spill) = spill { + for sc in spill.chars() { + tokens.push(PatternToken { + token: Token::Literal(sc), + count: 1, + }); + } + } } - output + + tokens }