use crate::endian::Endpoint;
use crate::format::Format;
pub const SHIM_FORMATS: [Format; 8] = [
Format::BIN,
Format::OCT,
Format::DEC,
Format::HEX,
Format::Char,
Format::B64,
Format::B32,
Format::Esc,
];
const CORE_BASES: [(Format, &str); 4] = [
(Format::BIN, "2"),
(Format::OCT, "8"),
(Format::DEC, "10"),
(Format::HEX, "16"),
];
pub const SELF_NAMES: [&str; 2] = ["from2to", "f2t"];
pub const SHORT_NAME: &str = "f2t";
pub const DETECT_NAME: &str = "whatbase";
const LE_SHIMS: [(&str, Endpoint, Endpoint); 14] = [
("lehex2hex", Endpoint::little(Format::HEX), Endpoint::big(Format::HEX)),
("lehex2dec", Endpoint::little(Format::HEX), Endpoint::big(Format::DEC)),
("lehex2bin", Endpoint::little(Format::HEX), Endpoint::big(Format::BIN)),
("lehex2char", Endpoint::little(Format::HEX), Endpoint::big(Format::Char)),
("lebin2hex", Endpoint::little(Format::BIN), Endpoint::big(Format::HEX)),
("lebin2dec", Endpoint::little(Format::BIN), Endpoint::big(Format::DEC)),
("ledec2hex", Endpoint::little(Format::DEC), Endpoint::big(Format::HEX)),
("hex2lehex", Endpoint::big(Format::HEX), Endpoint::little(Format::HEX)),
("hex2lebin", Endpoint::big(Format::HEX), Endpoint::little(Format::BIN)),
("hex2ledec", Endpoint::big(Format::HEX), Endpoint::little(Format::DEC)),
("bin2lehex", Endpoint::big(Format::BIN), Endpoint::little(Format::HEX)),
("char2lehex", Endpoint::big(Format::Char), Endpoint::little(Format::HEX)),
("dec2lehex", Endpoint::big(Format::DEC), Endpoint::little(Format::HEX)),
("dec2lebin", Endpoint::big(Format::DEC), Endpoint::little(Format::BIN)),
];
pub fn shorthands() -> Vec<(String, Endpoint, Endpoint)> {
let mut out = Vec::new();
for (from, fd) in CORE_BASES {
for (to, td) in CORE_BASES {
out.push((format!("{fd}2{td}"), Endpoint::big(from), Endpoint::big(to)));
}
}
out
}
pub fn shim_names() -> Vec<(String, Endpoint, Endpoint)> {
let mut out = Vec::new();
for from in SHIM_FORMATS {
for to in SHIM_FORMATS {
if from != to || from.is_positional() {
out.push((
format!("{}2{}", from.name(), to.name()),
Endpoint::big(from),
Endpoint::big(to),
));
}
}
}
for (base, _) in CORE_BASES {
out.push((
format!("{}2ascii", base.name()),
Endpoint::big(base),
Endpoint::big(Format::Char),
));
out.push((
format!("ascii2{}", base.name()),
Endpoint::big(Format::Char),
Endpoint::big(base),
));
}
for (name, from, to) in LE_SHIMS {
out.push((name.to_string(), from, to));
}
out
}
pub fn basename(argv0: &str) -> String {
let path = std::path::Path::new(argv0);
path.file_stem()
.map(|s| s.to_string_lossy().to_ascii_lowercase())
.unwrap_or_else(|| argv0.to_ascii_lowercase())
}
pub fn resolve(cmd: &str) -> Option<(Endpoint, Endpoint)> {
let cmd = cmd.to_ascii_lowercase();
if SELF_NAMES.contains(&cmd.as_str()) {
return None;
}
for (name, from, to) in shorthands() {
if name == cmd {
return Some((from, to));
}
}
let mut found = None;
for (i, ch) in cmd.char_indices() {
if ch != '2' {
continue;
}
let (left, right) = (&cmd[..i], &cmd[i + 1..]);
if let (Some(f), Some(t)) = (Endpoint::parse(left), Endpoint::parse(right)) {
if found.is_some() {
return None; }
found = Some((f, t));
}
}
found
}
#[cfg(test)]
mod tests {
use super::*;
use crate::endian::Endian;
use std::collections::HashMap;
#[test]
fn resolves_word_names() {
let big = |f, t| Some((Endpoint::big(f), Endpoint::big(t)));
assert_eq!(resolve("hex2bin"), big(Format::HEX, Format::BIN));
assert_eq!(resolve("dec2char"), big(Format::DEC, Format::Char));
assert_eq!(resolve("dec2ascii"), big(Format::DEC, Format::Char));
assert_eq!(resolve("b642hex"), big(Format::B64, Format::HEX));
assert_eq!(resolve("char2b32"), big(Format::Char, Format::B32));
}
#[test]
fn resolves_numeric_shorthands() {
let big = |f, t| Some((Endpoint::big(f), Endpoint::big(t)));
assert_eq!(resolve("1628"), big(Format::HEX, Format::OCT));
assert_eq!(resolve("10216"), big(Format::DEC, Format::HEX));
assert_eq!(resolve("2216"), big(Format::BIN, Format::HEX));
assert_eq!(resolve("822"), big(Format::OCT, Format::BIN));
}
#[test]
fn self_names_are_not_conversions() {
assert_eq!(resolve("f2t"), None);
assert_eq!(resolve("from2to"), None);
assert_eq!(resolve(DETECT_NAME), None);
}
#[test]
fn every_shorthand_has_exactly_one_parse() {
let bases = ["2", "8", "10", "16"];
for (name, from, to) in shorthands() {
let parses: Vec<_> = name
.char_indices()
.filter(|(_, c)| *c == '2')
.filter_map(|(i, _)| {
let (l, r) = (&name[..i], &name[i + 1..]);
(bases.contains(&l) && bases.contains(&r)).then(|| (l.to_string(), r.to_string()))
})
.collect();
assert_eq!(parses.len(), 1, "{name} has {} parses: {parses:?}", parses.len());
assert_eq!(resolve(&name), Some((from, to)), "{name} resolved wrong");
}
}
#[test]
fn shim_names_are_unique_and_resolve_back() {
let names = shim_names();
let mut seen: HashMap<&str, ()> = HashMap::new();
for (name, from, to) in &names {
assert!(seen.insert(name, ()).is_none(), "duplicate shim {name}");
assert_eq!(resolve(name), Some((*from, *to)), "{name} resolved wrong");
}
assert_eq!(names.len(), 82);
}
#[test]
fn shorthands_resolve_but_are_never_installed() {
let hex2oct = Some((Endpoint::big(Format::HEX), Endpoint::big(Format::OCT)));
assert_eq!(resolve("1628"), hex2oct);
let installed = shim_names();
for (name, _, _) in shorthands() {
assert!(
!installed.iter().any(|(n, _, _)| *n == name),
"{name} must not be installed as a command"
);
}
}
#[test]
fn resolves_endian_prefixes() {
let l = Endpoint::little;
let b = Endpoint::big;
assert_eq!(resolve("lehex2bin"), Some((l(Format::HEX), b(Format::BIN))));
assert_eq!(resolve("hex2lebin"), Some((b(Format::HEX), l(Format::BIN))));
assert_eq!(resolve("lehex2ledec"), Some((l(Format::HEX), l(Format::DEC))));
assert_eq!(resolve("leb642hex"), Some((l(Format::B64), b(Format::HEX))));
assert_eq!(resolve("char2lehex"), Some((b(Format::Char), l(Format::HEX))));
assert_eq!(resolve("behex2dec"), Some((b(Format::HEX), b(Format::DEC))));
assert_eq!(resolve("le1628"), Some((l(Format::HEX), b(Format::OCT))));
}
#[test]
fn a_bare_endian_prefix_is_not_a_conversion() {
for cmd in ["le2hex", "hex2le", "le2be", "be2be", "2le", "le2"] {
assert_eq!(resolve(cmd), None, "`{cmd}` must not resolve");
}
}
fn all_splits(cmd: &str) -> Vec<(Endpoint, Endpoint)> {
cmd.char_indices()
.filter(|(_, c)| *c == '2')
.filter_map(|(i, _)| {
Some((Endpoint::parse(&cmd[..i])?, Endpoint::parse(&cmd[i + 1..])?))
})
.collect()
}
#[test]
fn an_endian_prefix_never_changes_how_a_name_splits() {
for s in Format::SPELLINGS {
assert!(
!s.starts_with("le") && !s.starts_with("be"),
"the spelling `{s}` shadows an endian prefix"
);
assert!(
!(s.contains('2') && s.contains('l')),
"the spelling `{s}` holds both a 2 and an l, which breaks the proof"
);
}
let names: Vec<String> = shim_names()
.into_iter()
.chain(shorthands())
.filter(|(_, f, t)| f.endian == Endian::Big && t.endian == Endian::Big)
.map(|(n, _, _)| n)
.collect();
for name in &names {
let plain = all_splits(name);
assert_eq!(plain.len(), 1, "{name} already splits {} ways", plain.len());
let i = name
.char_indices()
.filter(|(_, c)| *c == '2')
.find(|&(i, _)| {
Endpoint::parse(&name[..i]).is_some()
&& Endpoint::parse(&name[i + 1..]).is_some()
})
.map(|(i, _)| i)
.unwrap();
let (l, r) = (&name[..i], &name[i + 1..]);
for (decorated, want) in [
(format!("le{l}2{r}"), (Endian::Little, Endian::Big)),
(format!("be{l}2{r}"), (Endian::Big, Endian::Big)),
(format!("{l}2le{r}"), (Endian::Big, Endian::Little)),
(format!("{l}2be{r}"), (Endian::Big, Endian::Big)),
(format!("le{l}2le{r}"), (Endian::Little, Endian::Little)),
(format!("be{l}2le{r}"), (Endian::Big, Endian::Little)),
] {
let got = all_splits(&decorated);
assert_eq!(got.len(), 1, "{decorated} splits {} ways: {got:?}", got.len());
assert_eq!(got[0].0.format, plain[0].0.format, "{decorated} from");
assert_eq!(got[0].1.format, plain[0].1.format, "{decorated} to");
assert_eq!((got[0].0.endian, got[0].1.endian), want, "{decorated} endian");
assert_eq!(resolve(&decorated), Some(got[0]), "{decorated} resolved wrong");
}
}
}
#[test]
fn prefixes_do_not_stack() {
for cmd in ["lelehex2hex", "beleb2hex", "hex2lelebin"] {
assert_eq!(resolve(cmd), None, "`{cmd}` must not resolve");
}
}
#[test]
fn only_little_endian_shims_are_installed() {
for (name, from, to) in shim_names() {
assert!(
!name.starts_with("be") && !name.contains("2be"),
"{name}: `be` is the identity and never earns a file"
);
assert_eq!(resolve(&name), Some((from, to)), "{name} resolved wrong");
}
}
#[test]
fn basename_strips_path_and_extension() {
assert_eq!(basename("/usr/local/bin/dec2char"), "dec2char");
assert_eq!(basename("hex2bin"), "hex2bin");
assert_eq!(basename("HEX2BIN.EXE"), "hex2bin");
#[cfg(windows)]
assert_eq!(basename(r"C:\Users\x\.cargo\bin\hex2bin.exe"), "hex2bin");
#[cfg(not(windows))]
assert_eq!(basename("/home/you/.cargo/bin/hex2bin"), "hex2bin");
}
}