use std::collections::HashSet;
use num_bigint::BigUint;
use crate::basen::{decode_base_n, encode_base_n, pow_biguint};
use crate::checksum::calculate_checksum;
use crate::error::{BasehError, ErrorCode};
use crate::feistel::{inverse_permute, permute};
use crate::profile::{
effective_checksum_length, prepare_profile, Mode, Permutation, PreparedProfile, Profile,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfusionProfile {
#[default]
None,
Light,
Medium,
Heavy,
}
impl ConfusionProfile {
fn map(self) -> &'static [(char, &'static [char])] {
match self {
ConfusionProfile::None => &[],
ConfusionProfile::Light => {
&[('B', &['D']), ('D', &['B']), ('P', &['T']), ('T', &['P'])]
}
ConfusionProfile::Medium => &[
('B', &['D']),
('D', &['B']),
('P', &['T']),
('T', &['P']),
('M', &['N']),
('N', &['M']),
('V', &['W']),
('W', &['V']),
],
ConfusionProfile::Heavy => &[
('B', &['D']),
('D', &['B']),
('P', &['T']),
('T', &['P']),
('M', &['N']),
('N', &['M']),
('V', &['W']),
('W', &['V']),
('F', &['S']),
('S', &['F']),
('C', &['G']),
('G', &['C']),
],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodeOptions {
pub accept_spaces: bool,
pub try_correction: bool,
pub confusion_profile: ConfusionProfile,
pub max_corrections: u32,
}
impl Default for DecodeOptions {
fn default() -> Self {
DecodeOptions {
accept_spaces: false,
try_correction: false,
confusion_profile: ConfusionProfile::None,
max_corrections: 1,
}
}
}
impl DecodeOptions {
pub fn strict() -> Self {
DecodeOptions::default()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodeResult {
pub id: BigUint,
pub canonical_code: String,
pub corrected: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidateOutcome {
pub valid: bool,
pub canonical_code: Option<String>,
pub reason: Option<ErrorCode>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum InspectResult {
Empty,
Typing { typed: String, progress: f64 },
BadChar,
TooLong,
Invalid { reason: ErrorCode },
Valid { id: BigUint, canonical_code: String },
}
impl InspectResult {
pub fn state(&self) -> &'static str {
match self {
InspectResult::Empty => "empty",
InspectResult::Typing { .. } => "typing",
InspectResult::BadChar => "bad-char",
InspectResult::TooLong => "too-long",
InspectResult::Invalid { .. } => "invalid",
InspectResult::Valid { .. } => "valid",
}
}
}
const MAX_CANDIDATES: usize = 64;
fn is_ascii_ws(c: char) -> bool {
matches!(c, '\t' | '\n' | '\x0B' | '\x0C' | '\r' | ' ')
}
fn normalize(
input: &str,
profile: &PreparedProfile,
accept_spaces: bool,
) -> Result<Vec<char>, BasehError> {
let trimmed = input.trim_matches(is_ascii_ws);
let had_separator =
!profile.profile.separator.is_empty() && trimmed.contains(&profile.profile.separator);
let mut s: String = if profile.profile.separator.is_empty() {
trimmed.to_string()
} else {
trimmed.replace(&profile.profile.separator, "")
};
if accept_spaces {
s = s.replace(' ', "");
}
let p = &profile.profile;
let allowed: HashSet<char> = profile
.body_alphabet_norm
.iter()
.chain(profile.checksum_alphabet_norm.iter())
.copied()
.collect();
let normalized: Vec<char> = s
.chars()
.map(|c| {
let c = if p.case_sensitive {
c
} else {
c.to_ascii_uppercase()
};
if allowed.contains(&c) {
c
} else {
*profile.aliases_norm.get(&c).unwrap_or(&c)
}
})
.collect();
for ch in &normalized {
if !allowed.contains(ch) {
return Err(BasehError::customer(
ErrorCode::InvalidCharacter,
format!("Symbol {ch:?} is not accepted"),
));
}
}
if p.mode == Mode::Expandable {
if normalized.len() < profile.min_length {
return Err(BasehError::customer(
ErrorCode::InvalidLength,
format!(
"Expected at least {} symbols, got {}",
profile.min_length,
normalized.len()
),
));
}
if normalized.len() > 32 {
return Err(BasehError::customer(
ErrorCode::InvalidLength,
format!("Expected at most 32 symbols, got {}", normalized.len()),
));
}
if had_separator && normalized.len() < profile.separator_min_length {
return Err(BasehError::customer(
ErrorCode::InvalidCharacter,
format!(
"Separators do not appear below {} symbols",
profile.separator_min_length
),
));
}
return Ok(normalized);
}
let expected = p.body_length + p.checksum_length;
let mut normalized = normalized;
if normalized.len() < expected && normalized.len() >= p.checksum_length.max(1) {
let zero = profile.body_alphabet_norm[0];
let mut padded = vec![zero; expected - normalized.len()];
padded.extend(normalized);
normalized = padded;
}
if normalized.len() != expected {
return Err(BasehError::customer(
ErrorCode::InvalidLength,
format!("Expected {} symbols, got {}", expected, normalized.len()),
));
}
Ok(normalized)
}
fn format_raw(raw: &[char], profile: &PreparedProfile) -> String {
let p = &profile.profile;
if p.separator.is_empty() {
return raw.iter().collect();
}
if p.mode == Mode::Expandable {
if raw.len() < profile.separator_min_length {
return raw.iter().collect();
}
return format_with(raw, &expandable_grouping(raw.len()), &p.separator);
}
format_with(raw, &p.grouping, &p.separator)
}
fn format_with(raw: &[char], sizes: &[usize], separator: &str) -> String {
let mut parts: Vec<String> = Vec::with_capacity(sizes.len());
let mut offset = 0;
for size in sizes {
parts.push(raw[offset..offset + size].iter().collect());
offset += size;
}
parts.join(separator)
}
fn format_partial(raw: &[char], profile: &PreparedProfile) -> String {
let p = &profile.profile;
if p.separator.is_empty() {
return raw.iter().collect();
}
if p.mode == Mode::Expandable {
if raw.len() < profile.separator_min_length {
return raw.iter().collect();
}
return format_with(raw, &expandable_grouping(raw.len()), &p.separator);
}
let mut parts: Vec<String> = Vec::new();
let mut offset = 0;
for size in &p.grouping {
if offset >= raw.len() {
break;
}
let end = (offset + size).min(raw.len());
parts.push(raw[offset..end].iter().collect());
offset = end;
}
parts.join(&p.separator)
}
pub fn expandable_grouping(length: usize) -> Vec<usize> {
let g = length.div_ceil(5);
let g = g.max(2);
let base = length / g;
if base < 1 {
return vec![length];
}
let rem = length % g;
let mut sizes = vec![base + 1; rem];
sizes.extend(std::iter::repeat_n(base, g - rem));
sizes
}
pub(crate) fn generation_base(profile: &PreparedProfile, length: usize) -> BigUint {
let mut base = BigUint::from(0u64);
for l in profile.min_length..length {
base += generation_capacity(profile, l);
}
base
}
pub(crate) fn generation_capacity(profile: &PreparedProfile, length: usize) -> BigUint {
pow_biguint(
BigUint::from(profile.body_alphabet_norm.len() as u64),
length - effective_checksum_length(profile, length),
)
}
pub(crate) fn generation_for_id(
profile: &PreparedProfile,
id: &BigUint,
) -> Result<usize, BasehError> {
let mut l = profile.min_length;
let mut base = BigUint::from(0u64);
let mut cap = generation_capacity(profile, l);
while *id >= &base + &cap {
if l >= 32 {
return Err(BasehError::customer(
ErrorCode::OutOfRange,
format!("ID {id} requires a code longer than 32 symbols"),
));
}
base += ∩
l += 1;
cap = generation_capacity(profile, l);
}
Ok(l)
}
fn generate_candidates(
body: &[char],
confusion: &[(char, Vec<char>)],
max_edits: u32,
) -> Result<Vec<Vec<char>>, BasehError> {
if max_edits == 0 {
return Ok(Vec::new());
}
let mut results: Vec<Vec<char>> = Vec::new();
let mut seen: HashSet<Vec<char>> = HashSet::new();
for pos in 0..body.len() {
let source = body[pos];
for (map_source, replacements) in confusion {
if *map_source != source {
continue;
}
for replacement in replacements.iter() {
let mut candidate = body.to_vec();
candidate[pos] = *replacement;
if seen.insert(candidate.clone()) {
results.push(candidate);
if results.len() > MAX_CANDIDATES {
return Err(BasehError::new(
ErrorCode::TooManyCandidates,
"Candidate generation exceeded 64 entries",
false,
));
}
}
}
}
}
Ok(results)
}
pub struct Baseh {
profile: PreparedProfile,
}
impl Baseh {
pub fn new(profile: Profile) -> Result<Baseh, BasehError> {
Ok(Baseh {
profile: prepare_profile(profile)?,
})
}
pub fn capacity(&self) -> Result<&BigUint, BasehError> {
if self.profile.profile.mode != Mode::Fixed {
return Err(BasehError::new(
ErrorCode::InvalidProfile,
"capacity() is only defined for fixed-mode profiles",
false,
));
}
Ok(&self.profile.capacity)
}
pub fn generation_base(&self, length: usize) -> BigUint {
generation_base(&self.profile, length)
}
pub fn generation_capacity(&self, length: usize) -> BigUint {
generation_capacity(&self.profile, length)
}
pub fn generation_for_id(&self, id: &BigUint) -> Result<usize, BasehError> {
generation_for_id(&self.profile, id)
}
pub fn effective_checksum_length(&self, length: usize) -> usize {
effective_checksum_length(&self.profile, length)
}
pub fn profile(&self) -> &Profile {
&self.profile.profile
}
fn encode_fixed(&self, id: &BigUint) -> Result<String, BasehError> {
if *id >= self.profile.capacity {
return Err(BasehError::customer(
ErrorCode::OutOfRange,
format!("ID {id} is outside the profile capacity"),
));
}
let p = &self.profile.profile;
let mut value = id.clone();
if let Permutation::FeistelV1 {
key_bytes, rounds, ..
} = &p.permutation
{
value = permute(
&value,
&self.profile.capacity,
&p.profile_id,
key_bytes,
*rounds,
None,
)?;
}
let body = encode_base_n(&value, &self.profile.body_alphabet_norm, p.body_length);
let raw = self.finish_encode(body, p.checksum_length)?;
Ok(format_raw(&raw, &self.profile))
}
fn encode_expandable(&self, id: &BigUint) -> Result<String, BasehError> {
let l = generation_for_id(&self.profile, id)?;
let p = &self.profile.profile;
let mut value = id - generation_base(&self.profile, l);
let domain = generation_capacity(&self.profile, l);
if let Permutation::FeistelV1 {
key_bytes, rounds, ..
} = &p.permutation
{
value = permute(
&value,
&domain,
&p.profile_id,
key_bytes,
*rounds,
Some(l as u32),
)?;
}
let k = effective_checksum_length(&self.profile, l);
let body = encode_base_n(&value, &self.profile.body_alphabet_norm, l - k);
let raw = self.finish_encode(body, k)?;
Ok(format_raw(&raw, &self.profile))
}
fn finish_encode(&self, body: String, checksum_length: usize) -> Result<Vec<char>, BasehError> {
let body_chars: Vec<char> = body.chars().collect();
let checksum = calculate_checksum(&self.profile, &body_chars, checksum_length)?;
let mut raw = body_chars;
raw.extend(checksum.chars());
if !self.profile.blocklist.is_empty() {
let upper: String = raw
.iter()
.map(|c| c.to_ascii_uppercase())
.collect::<String>();
if self.profile.blocklist.iter().any(|w| upper.contains(w)) {
return Err(BasehError::new(
ErrorCode::BlockedCode,
"The generated reference contains a blocked substring",
false,
));
}
}
let max = self.profile.profile.max_repetition;
if max > 0 {
let mut run = 1;
for pair in raw.windows(2) {
run = if pair[0] == pair[1] { run + 1 } else { 1 };
if run >= max {
return Err(BasehError::new(
ErrorCode::BlockedCode,
"The generated reference repeats a symbol beyond the profile limit",
false,
));
}
}
}
Ok(raw)
}
pub fn encode(&self, id: &BigUint) -> Result<String, BasehError> {
match self.profile.profile.mode {
Mode::Fixed => self.encode_fixed(id),
Mode::Expandable => self.encode_expandable(id),
}
}
pub fn decode(&self, input: &str, options: &DecodeOptions) -> Result<DecodeResult, BasehError> {
let raw = normalize(input, &self.profile, options.accept_spaces)?;
let p = &self.profile.profile;
let effective_k = match p.mode {
Mode::Expandable => effective_checksum_length(&self.profile, raw.len()),
Mode::Fixed => p.checksum_length,
};
let body_length = match p.mode {
Mode::Expandable => raw.len() - effective_k,
Mode::Fixed => p.body_length,
};
let mut body: Vec<char> = raw[..body_length].to_vec();
let supplied_checksum: Vec<char> = raw[body_length..].to_vec();
if calculate_checksum(&self.profile, &body, effective_k)?
!= supplied_checksum.iter().collect::<String>()
{
if !options.try_correction || options.max_corrections == 0 {
return Err(BasehError::customer(
ErrorCode::InvalidChecksum,
"The reference code did not pass validation",
));
}
let body_set: HashSet<char> = self.profile.body_alphabet_norm.iter().copied().collect();
let filtered_map: Vec<(char, Vec<char>)> = options
.confusion_profile
.map()
.iter()
.filter_map(|(source, replacements)| {
let kept: Vec<char> = replacements
.iter()
.copied()
.filter(|r| body_set.contains(r))
.collect();
if kept.is_empty() {
None
} else {
Some((*source, kept))
}
})
.collect();
let candidates = generate_candidates(&body, &filtered_map, options.max_corrections)?;
let mut valid: Option<Vec<char>> = None;
for candidate in candidates {
let candidate_checksum =
calculate_checksum(&self.profile, &candidate, effective_k)?;
if candidate_checksum == supplied_checksum.iter().collect::<String>() {
if valid.is_some() {
return Err(BasehError::new(
ErrorCode::AmbiguousInput,
"The reference code matches more than one record",
false,
));
}
valid = Some(candidate);
}
}
match valid {
Some(candidate) => body = candidate,
None => {
return Err(BasehError::customer(
ErrorCode::InvalidChecksum,
"The reference code did not pass validation",
));
}
}
}
let mut value = decode_base_n(
&body,
self.profile.body_alphabet_norm.len(),
&self.profile.body_index,
)?;
if p.mode == Mode::Expandable {
let l = raw.len();
if let Permutation::FeistelV1 {
key_bytes, rounds, ..
} = &p.permutation
{
value = inverse_permute(
&value,
&generation_capacity(&self.profile, l),
&p.profile_id,
key_bytes,
*rounds,
Some(l as u32),
)?;
}
value = generation_base(&self.profile, l) + value;
} else if let Permutation::FeistelV1 {
key_bytes, rounds, ..
} = &p.permutation
{
value = inverse_permute(
&value,
&self.profile.capacity,
&p.profile_id,
key_bytes,
*rounds,
None,
)?;
}
let canonical_code = self.encode(&value)?;
let canonical_raw: Vec<char> = if p.separator.is_empty() {
canonical_code.chars().collect()
} else {
canonical_code.replace(&p.separator, "").chars().collect()
};
Ok(DecodeResult {
id: value,
canonical_code,
corrected: raw != canonical_raw,
})
}
pub fn inspect(&self, input: &str) -> InspectResult {
let p = &self.profile.profile;
let no_sep = if p.separator.is_empty() {
input.to_string()
} else {
input.replace(&p.separator, "")
};
let cleaned: Vec<char> = no_sep.chars().filter(|c| !is_ascii_ws(*c)).collect();
let typed_count = cleaned.len();
if typed_count == 0 {
return InspectResult::Empty;
}
let fixed = p.mode == Mode::Fixed;
let expected = if fixed {
p.body_length + p.checksum_length
} else {
32
};
if typed_count > expected {
return InspectResult::TooLong;
}
let allowed: HashSet<char> = self
.profile
.body_alphabet_norm
.iter()
.chain(self.profile.checksum_alphabet_norm.iter())
.copied()
.collect();
let normalized: Vec<char> = cleaned
.iter()
.map(|c| {
let c = if p.case_sensitive {
*c
} else {
c.to_ascii_uppercase()
};
if allowed.contains(&c) {
c
} else {
*self.profile.aliases_norm.get(&c).unwrap_or(&c)
}
})
.collect();
if normalized.iter().any(|c| !allowed.contains(c)) {
return InspectResult::BadChar;
}
let complete = if fixed {
typed_count == expected
} else {
typed_count >= self.profile.min_length
};
if !complete {
let denominator = if fixed {
expected
} else {
self.profile.min_length
};
return InspectResult::Typing {
typed: format_partial(&normalized, &self.profile),
progress: typed_count as f64 / denominator as f64,
};
}
let raw: String = normalized.iter().collect();
let options = DecodeOptions::default();
let outcome = self.validate(&raw, &options);
if !outcome.valid {
return InspectResult::Invalid {
reason: outcome.reason.unwrap_or(ErrorCode::InvalidChecksum),
};
}
let decoded = self
.decode(&raw, &options)
.expect("validate passed, so decode cannot fail on the same input");
InspectResult::Valid {
id: decoded.id,
canonical_code: decoded.canonical_code,
}
}
pub fn validate(&self, input: &str, options: &DecodeOptions) -> ValidateOutcome {
match self.decode(input, options) {
Ok(result) => ValidateOutcome {
valid: true,
canonical_code: Some(result.canonical_code),
reason: None,
},
Err(err) => ValidateOutcome {
valid: false,
canonical_code: None,
reason: Some(err.code),
},
}
}
}