use std::collections::HashSet;
use num_bigint::BigUint;
use crate::basen::{decode_base_n, encode_base_n};
use crate::checksum::calculate_checksum;
use crate::error::{BasehError, ErrorCode};
use crate::feistel::{inverse_permute, permute};
use crate::profile::{prepare_profile, 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, Default)]
pub struct DecodeOptions {
pub accept_spaces: bool,
pub try_correction: bool,
pub confusion_profile: ConfusionProfile,
pub max_corrections: u32,
}
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>,
}
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 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 normalized: Vec<char> = s
.chars()
.map(|c| {
let c = if p.case_sensitive {
c
} else {
c.to_ascii_uppercase()
};
*profile.aliases_norm.get(&c).unwrap_or(&c)
})
.collect();
let allowed: HashSet<char> = profile
.body_alphabet_norm
.iter()
.chain(profile.checksum_alphabet_norm.iter())
.copied()
.collect();
for ch in &normalized {
if !allowed.contains(ch) {
return Err(BasehError::customer(
ErrorCode::InvalidCharacter,
format!("Symbol {ch:?} is not accepted"),
));
}
}
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();
}
let mut parts: Vec<String> = Vec::with_capacity(p.grouping.len());
let mut offset = 0;
for size in &p.grouping {
parts.push(raw[offset..offset + size].iter().collect());
offset += size;
}
parts.join(&p.separator)
}
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) -> &BigUint {
&self.profile.capacity
}
pub fn profile(&self) -> &Profile {
&self.profile.profile
}
pub fn encode(&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,
)?;
}
let body = encode_base_n(&value, &self.profile.body_alphabet_norm, p.body_length);
let body_chars: Vec<char> = body.chars().collect();
let checksum = calculate_checksum(&self.profile, &body_chars)?;
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,
));
}
}
Ok(format_raw(&raw, &self.profile))
}
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 mut body: Vec<char> = raw[..p.body_length].to_vec();
let supplied_checksum: Vec<char> = raw[p.body_length..].to_vec();
if calculate_checksum(&self.profile, &body)? != 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: HashSet<Vec<char>> = HashSet::new();
for candidate in candidates {
let candidate_checksum = calculate_checksum(&self.profile, &candidate)?;
if candidate_checksum == supplied_checksum.iter().collect::<String>() {
valid.insert(candidate);
}
}
if valid.is_empty() {
return Err(BasehError::customer(
ErrorCode::InvalidChecksum,
"The reference code did not pass validation",
));
}
if valid.len() > 1 {
return Err(BasehError::new(
ErrorCode::AmbiguousInput,
"The reference code matches more than one record",
false,
));
}
body = valid
.into_iter()
.next()
.expect("exactly one valid candidate");
}
let mut value = decode_base_n(
&body,
self.profile.body_alphabet_norm.len(),
&self.profile.body_index,
)?;
if let Permutation::FeistelV1 {
key_bytes, rounds, ..
} = &p.permutation
{
value = inverse_permute(
&value,
&self.profile.capacity,
&p.profile_id,
key_bytes,
*rounds,
)?;
}
let canonical_code = self.encode(&value)?;
let canonical_raw: Vec<char> = canonical_code
.chars()
.filter(|c| !p.separator.contains(*c))
.collect();
Ok(DecodeResult {
id: value,
canonical_code,
corrected: raw != canonical_raw,
})
}
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),
},
}
}
}