use core::fmt;
use subtle::ConstantTimeEq;
use crate::error::Error;
use crate::random::Random;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodeAlphabet {
pub chars: String,
pub len: usize,
}
impl CodeAlphabet {
pub fn pin() -> Self {
Self {
chars: "0123456789".to_owned(),
len: 6,
}
}
pub fn user_code() -> Self {
Self {
chars: "BCDFGHJKLMNPQRSTVWXZ".to_owned(),
len: 8,
}
}
pub fn combinations(&self) -> u128 {
let base = self.chars.chars().count() as u128;
u32::try_from(self.len)
.ok()
.and_then(|len| base.checked_pow(len))
.unwrap_or(u128::MAX)
}
pub fn check(&self) -> Result<(), Error> {
let chars: Vec<char> = self.chars.chars().collect();
let repeated = chars
.iter()
.enumerate()
.any(|(index, c)| chars[..index].contains(c));
if chars.is_empty() || repeated || chars.iter().any(|c| c.is_control()) || self.len == 0 {
return Err(Error::InvalidOptions);
}
Ok(())
}
pub(crate) fn generate(&self, random: &Random) -> Result<String, Error> {
self.check()?;
let chars: Vec<char> = self.chars.chars().collect();
let mut code = String::with_capacity(self.len);
for _ in 0..self.len {
code.push(chars[below(random, chars.len())?]);
}
Ok(code)
}
pub(crate) fn parse(&self, text: &str) -> Result<String, Error> {
self.check()?;
if text.chars().count() != self.len || !text.chars().all(|c| self.chars.contains(c)) {
return Err(Error::InvalidCode);
}
Ok(text.to_owned())
}
}
pub(crate) fn below(random: &Random, bound: usize) -> Result<usize, Error> {
let bound = u64::try_from(bound.max(1)).unwrap_or(u64::MAX);
let span = 1u64 << 32;
let limit = span - span % bound;
loop {
let mut bytes = [0u8; 4];
random.fill(&mut bytes)?;
let value = u64::from(u32::from_be_bytes(bytes));
if value < limit {
return Ok(usize::try_from(value % bound).unwrap_or(0));
}
}
}
pub(crate) fn same(left: &str, right: &str) -> bool {
left.len() == right.len() && bool::from(left.as_bytes().ct_eq(right.as_bytes()))
}
#[derive(Clone, PartialEq, Eq)]
pub struct Pin(String);
impl Pin {
pub fn generate(alphabet: &CodeAlphabet, random: &Random) -> Result<Self, Error> {
alphabet.generate(random).map(Self)
}
pub fn parse(alphabet: &CodeAlphabet, text: &str) -> Result<Self, Error> {
alphabet.parse(text).map(Self)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Drop for Pin {
fn drop(&mut self) {
zeroize::Zeroize::zeroize(&mut self.0);
}
}
impl fmt::Debug for Pin {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Pin(..)")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairingCode {
pub slot: Option<u8>,
pub pin: Pin,
}
#[derive(Clone, PartialEq, Eq)]
pub struct UserCode(String);
impl UserCode {
pub(crate) fn issued(text: String) -> Self {
Self(text)
}
pub fn generate(alphabet: &CodeAlphabet, random: &Random) -> Result<Self, Error> {
alphabet.generate(random).map(Self)
}
pub fn parse(alphabet: &CodeAlphabet, text: &str) -> Result<Self, Error> {
alphabet.parse(text).map(Self)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for UserCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("UserCode(..)")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes_match_exactly_over_their_alphabet() {
let alphabet = CodeAlphabet::user_code();
assert!(UserCode::parse(&alphabet, "WDJBMJHT").is_ok());
for bad in [
"wdjbmjht",
"WDJB-MJHT",
"WDJB MJHT",
"WDJBMJH",
"WDJBMJHTA",
"AAAAAAAA",
] {
assert!(matches!(
UserCode::parse(&alphabet, bad),
Err(Error::InvalidCode)
));
}
assert!(Pin::parse(&CodeAlphabet::pin(), "482913").is_ok());
assert!(Pin::parse(&CodeAlphabet::pin(), "48291a").is_err());
}
#[test]
fn combinations_are_reported_not_refused() {
assert_eq!(CodeAlphabet::pin().combinations(), 1_000_000);
assert_eq!(CodeAlphabet::user_code().combinations(), 20u128.pow(8));
let tiny = CodeAlphabet {
chars: "01".to_owned(),
len: 1,
};
assert!(tiny.check().is_ok());
assert_eq!(tiny.combinations(), 2);
let huge = CodeAlphabet {
chars: "01".to_owned(),
len: 1000,
};
assert_eq!(huge.combinations(), u128::MAX);
}
#[test]
fn meaningless_alphabets_are_errors() {
for (chars, len) in [("", 6), ("0123", 0), ("0012", 4), ("01\n", 4)] {
let alphabet = CodeAlphabet {
chars: chars.to_owned(),
len,
};
assert!(matches!(alphabet.check(), Err(Error::InvalidOptions)));
}
}
#[test]
fn generated_codes_use_the_whole_alphabet() {
let counter = core::sync::atomic::AtomicU32::new(0);
let random = Random::from_fn(move |out| {
let value = counter.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
out.copy_from_slice(&value.to_be_bytes()[..out.len()]);
Ok(())
});
let alphabet = CodeAlphabet::pin();
let code = Pin::generate(&alphabet, &random).unwrap();
assert_eq!(code.as_str(), "012345");
assert!(Pin::parse(&alphabet, code.as_str()).is_ok());
}
}