Compare commits
21 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fb78242ae | ||
| 03f35f0b35 | |||
|
|
29a68bc047 | ||
|
|
f428ac59e0 | ||
|
|
6c644d1256 | ||
|
|
ca1e27a84e | ||
|
|
b68815c29c | ||
|
|
5ac61418a9 | ||
|
|
aeb3cfb71e | ||
|
|
2c11db2d28 | ||
|
|
a38fb7aa9d | ||
|
|
654aafe120 | ||
|
|
6abc1ee35d | ||
|
|
96bacd47bf | ||
|
|
f9a479f4b5 | ||
|
|
7af9a92785 | ||
|
|
e0d66a31f0 | ||
|
|
0d9519c0db | ||
|
|
32734cc91c | ||
|
|
192daf589d | ||
|
|
91a3bb3643 |
10 changed files with 524 additions and 156 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -5,3 +5,5 @@ pkg/*.pkg.tar.zst
|
|||
pkg/*.tar.gz
|
||||
pkg/pkg/
|
||||
pkg/src/
|
||||
result/
|
||||
flake.lock
|
||||
|
|
|
|||
6
Cargo.lock
generated
6
Cargo.lock
generated
|
|
@ -144,7 +144,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "dolltool"
|
||||
version = "1.3.0"
|
||||
version = "1.4.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"num-bigint",
|
||||
|
|
@ -340,9 +340,9 @@ checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"
|
|||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.27"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
license = "GPL-3.0-or-later"
|
||||
name = "dolltool"
|
||||
version = "1.3.0"
|
||||
version = "1.4.0"
|
||||
authors = ["ika4422"]
|
||||
description = "A simple dollcode encoder, decoder, and generator inside your terminal :3"
|
||||
edition = "2024"
|
||||
|
|
|
|||
24
README.md
24
README.md
|
|
@ -13,6 +13,14 @@ This project was inspired by [noe](https://noe.sh/) and its [dollcode transcoder
|
|||
|
||||
## Installation
|
||||
|
||||
### Arch Linux
|
||||
|
||||
You can install this package from the AUR with the package name `dolltool`, or
|
||||
alternatively by cloning the repository and using `makepkg -si` inside the `pkg/`
|
||||
directory.
|
||||
|
||||
### Other
|
||||
|
||||
Clone the repository then `cd` into the directory and run:
|
||||
|
||||
```bash
|
||||
|
|
@ -67,9 +75,19 @@ hello world :3
|
|||
|
||||
Generates random codes based on a user-defined pattern:
|
||||
|
||||
- `n`: Number (0-9)
|
||||
- `l`: Letter (a-z)
|
||||
- `a`: 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
|
||||
|
|
|
|||
73
flake.nix
Normal file
73
flake.nix
Normal file
|
|
@ -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;
|
||||
});
|
||||
};
|
||||
});
|
||||
}
|
||||
24
pkg/PKGBUILD
Normal file
24
pkg/PKGBUILD
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# Maintainer: jaiden brooke <jaiden.lily.brooke@gmail.com>
|
||||
pkgname=dolltool
|
||||
pkgver=1.4.0
|
||||
pkgrel=1
|
||||
pkgdesc="A simple dollcode encoder, decoder, and generator inside your terminal"
|
||||
url=https://git.gay/ika4422/dolltool
|
||||
arch=('x86_64' 'aarch64')
|
||||
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=('d536e6b3d93ce85cc48780565f1ac461a424bf0deff64fc95d474af5bdee29ec')
|
||||
|
||||
build() {
|
||||
cd "$srcdir/../.."
|
||||
cargo build --release
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$srcdir/../.."
|
||||
|
||||
install -Dm755 "target/release/dolltool" "$pkgdir/usr/bin/dolltool"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
}
|
||||
112
src/commands.rs
Normal file
112
src/commands.rs
Normal file
|
|
@ -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<String> = 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<String> = 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
148
src/main.rs
148
src/main.rs
|
|
@ -15,143 +15,41 @@
|
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<String>,
|
||||
|
||||
#[arg(short, long)]
|
||||
/// Decodes the following dollcode into an integer or text
|
||||
decode: Option<String>,
|
||||
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
/// Specifies the encoding/decoding method as text, not as an integer
|
||||
text: bool,
|
||||
|
||||
#[arg(short, long)]
|
||||
/// Generates codes from a user-defined pattern (n = number; l = letter; a = alphanumeric)
|
||||
generate: Option<String>,
|
||||
|
||||
#[arg(short, long, default_value_t = 1)]
|
||||
/// Specifies how many codes to generate
|
||||
count: usize,
|
||||
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
/// Outputs generated letters as uppercase as opposed to lowercase
|
||||
upper: bool,
|
||||
|
||||
#[arg(long, default_value_t = false)]
|
||||
/// Will generate codes without encoding it into dollcode
|
||||
no_doll: bool,
|
||||
|
||||
#[arg(long)]
|
||||
/// Display the license for dolltool
|
||||
license: bool,
|
||||
}
|
||||
use crate::models::Args;
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
if let Some(pattern) = args.generate {
|
||||
for _ in 0..args.count {
|
||||
let generated = generate_from_pattern(&pattern, args.upper);
|
||||
|
||||
if args.no_doll {
|
||||
println!("{}", generated);
|
||||
} else {
|
||||
let as_num = if args.text {
|
||||
None
|
||||
} else {
|
||||
BigUint::parse_bytes(generated.as_bytes(), 10)
|
||||
};
|
||||
|
||||
match as_num {
|
||||
Some(num) => {
|
||||
println!("{} :: {}", generated, to_dollcode(num).unwrap());
|
||||
}
|
||||
None => {
|
||||
let doll: Vec<String> = generated
|
||||
.chars()
|
||||
.map(|c| to_dollcode(BigUint::from(c as u64)).unwrap())
|
||||
.collect();
|
||||
println!("{} :: {}", generated, doll.join(" "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(input) = args.encode {
|
||||
let encode_as_text = args.text || input.parse::<BigUint>().is_err();
|
||||
|
||||
if encode_as_text {
|
||||
let result: Vec<String> = input
|
||||
.chars()
|
||||
.map(|c| to_dollcode(BigUint::from(c as u64)).unwrap())
|
||||
.collect();
|
||||
println!("{}", result.join(" "));
|
||||
} else {
|
||||
let num = input.parse::<BigUint>().unwrap();
|
||||
|
||||
match to_dollcode(num) {
|
||||
Ok(code) => println!("{}", code),
|
||||
Err(e) => {
|
||||
eprintln!("Error: {}", e);
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} 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),
|
||||
Err(e) => {
|
||||
eprintln!("Error: {}", e);
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if args.license {
|
||||
println!("{}", include_str!("../LICENSE"));
|
||||
process::exit(1);
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
if args.tokens {
|
||||
println!("{}", pattern_gen::TOKEN_HELP);
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
if let Some(pattern) = args.generate {
|
||||
commands::run_generate(
|
||||
&pattern,
|
||||
args.count,
|
||||
args.base.radix(),
|
||||
args.no_doll,
|
||||
args.text,
|
||||
);
|
||||
} else if let Some(input) = args.encode {
|
||||
commands::run_encode(&input, args.base.radix(), args.text);
|
||||
} else if let Some(input) = args.decode {
|
||||
commands::run_decode(&input, args.base.radix(), args.text, args.all_bases);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
115
src/models.rs
Normal file
115
src/models.rs
Normal file
|
|
@ -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<String>,
|
||||
|
||||
#[arg(short, long, value_name = "DOLLCODE")]
|
||||
/// Decodes the following dollcode into an integer or text
|
||||
pub decode: Option<String>,
|
||||
|
||||
#[arg(short, long, value_name = "PATTERN")]
|
||||
/// Generates codes from a user-defined pattern (see --tokens for token list)
|
||||
pub generate: Option<String>,
|
||||
|
||||
#[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<Self, Self::Err> {
|
||||
// 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::<u32>()
|
||||
.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)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,31 +1,157 @@
|
|||
use rand::RngExt;
|
||||
|
||||
pub fn generate_from_pattern(pattern: &str, upper: bool) -> String {
|
||||
let mut rng = rand::rng();
|
||||
let mut output = String::new();
|
||||
pub const TOKEN_HELP: &str = "\
|
||||
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)
|
||||
|
||||
for c in pattern.chars() {
|
||||
match c {
|
||||
'n' => output.push(rng.random_range('0'..='9')),
|
||||
'l' => {
|
||||
let letter = rng.random_range('a'..='z');
|
||||
output.push(if upper {
|
||||
letter.to_ascii_uppercase()
|
||||
} else {
|
||||
letter
|
||||
});
|
||||
}
|
||||
'a' => {
|
||||
let pool = if upper {
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
} else {
|
||||
"0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
};
|
||||
let idx = rng.random_range(0..pool.len());
|
||||
output.push(pool.chars().nth(idx).unwrap());
|
||||
}
|
||||
_ => output.push(c),
|
||||
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
|
||||
}
|
||||
|
||||
fn pick_cased(rng: &mut impl rand::Rng, pool: &[u8], case: Case) -> char {
|
||||
let ch = pick(rng, pool);
|
||||
|
||||
match case {
|
||||
Case::Lower => ch,
|
||||
Case::Upper => ch.to_ascii_uppercase(),
|
||||
Case::Mixed => {
|
||||
if rng.random::<bool>() {
|
||||
ch.to_ascii_uppercase()
|
||||
} else {
|
||||
ch
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_case(chars: &mut std::iter::Peekable<impl Iterator<Item = char>>) -> Case {
|
||||
match chars.peek() {
|
||||
Some(&'^') => {
|
||||
chars.next();
|
||||
Case::Upper
|
||||
}
|
||||
Some(&'~') => {
|
||||
chars.next();
|
||||
Case::Mixed
|
||||
}
|
||||
_ => Case::Lower,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_pattern(pattern: &str) -> Vec<PatternToken> {
|
||||
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
|
||||
};
|
||||
|
||||
let (count, spill) = if chars.peek() == Some(&'{') {
|
||||
chars.next();
|
||||
let inner: String = chars.by_ref().take_while(|&x| x != '}').collect();
|
||||
|
||||
match inner.parse::<usize>() {
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokens
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue