use std::fmt;
use quickcheck::{Arbitrary, Gen};
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
pub enum Fingerprint {
V4([u8;20]),
Invalid(Box<[u8]>)
}
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.convert_to_string(true))
}
}
impl fmt::Debug for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Fingerprint")
.field(&self.to_string())
.finish()
}
}
impl fmt::UpperHex for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.convert_to_string(false))
}
}
impl fmt::LowerHex for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut hex = self.convert_to_string(false);
hex.make_ascii_lowercase();
f.write_str(&hex)
}
}
impl std::str::FromStr for Fingerprint {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(Self::from_bytes(&crate::fmt::hex::decode_pretty(s)?[..]))
}
}
impl Fingerprint {
pub fn from_bytes(raw: &[u8]) -> Fingerprint {
if raw.len() == 20 {
let mut fp : [u8; 20] = Default::default();
fp.copy_from_slice(raw);
Fingerprint::V4(fp)
} else {
Fingerprint::Invalid(raw.to_vec().into_boxed_slice())
}
}
pub fn as_slice(&self) -> &[u8] {
match self {
&Fingerprint::V4(ref fp) => fp,
&Fingerprint::Invalid(ref fp) => fp,
}
}
fn convert_to_string(&self, pretty: bool) -> String {
let raw = match self {
&Fingerprint::V4(ref fp) => &fp[..],
&Fingerprint::Invalid(ref fp) => &fp[..],
};
let mut output = Vec::with_capacity(
raw.len() * 2
+ if pretty {
raw.len() / 2
+ raw.len() / 10
} else { 0 });
for (i, b) in raw.iter().enumerate() {
if pretty && i > 0 && i % 2 == 0 {
output.push(' ' as u8);
}
if pretty && i > 0 && i % 10 == 0 {
output.push(' ' as u8);
}
let top = b >> 4;
let bottom = b & 0xFu8;
if top < 10u8 {
output.push('0' as u8 + top)
} else {
output.push('A' as u8 + (top - 10u8))
}
if bottom < 10u8 {
output.push('0' as u8 + bottom)
} else {
output.push('A' as u8 + (bottom - 10u8))
}
}
String::from_utf8(output).unwrap()
}
pub fn to_icao(&self) -> String {
let mut ret = String::default();
for ch in self.convert_to_string(false).chars() {
let word = match ch {
'0' => "Zero",
'1' => "One",
'2' => "Two",
'3' => "Three",
'4' => "Four",
'5' => "Five",
'6' => "Six",
'7' => "Seven",
'8' => "Eight",
'9' => "Niner",
'A' => "Alpha",
'B' => "Bravo",
'C' => "Charlie",
'D' => "Delta",
'E' => "Echo",
'F' => "Foxtrot",
_ => { continue; }
};
if !ret.is_empty() {
ret.push_str(" ");
}
ret.push_str(word);
}
ret
}
}
impl Arbitrary for Fingerprint {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
use rand::Rng;
let mut fp = [0; 20];
fp.iter_mut().for_each(|p| *p = g.gen());
Fingerprint::V4(fp)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn icao() {
let fpr = "0123 4567 89AB CDEF 0123 4567 89AB CDEF 0123 4567"
.parse::<Fingerprint>().unwrap();
let expected = "\
Zero One Two Three Four Five Six Seven Eight Niner Alpha Bravo Charlie Delta \
Echo Foxtrot Zero One Two Three Four Five Six Seven Eight Niner Alpha Bravo \
Charlie Delta Echo Foxtrot Zero One Two Three Four Five Six Seven";
assert_eq!(fpr.to_icao(), expected);
}
#[test]
fn hex_formatting() {
let fpr = "0123 4567 89AB CDEF 0123 4567 89AB CDEF 0123 4567"
.parse::<Fingerprint>().unwrap();
assert_eq!(format!("{:X}", fpr), "0123456789ABCDEF0123456789ABCDEF01234567");
assert_eq!(format!("{:x}", fpr), "0123456789abcdef0123456789abcdef01234567");
}
#[test]
fn fingerprint_is_send_and_sync() {
fn f<T: Send + Sync>(_: T) {}
f("0123 4567 89AB CDEF 0123 4567 89AB CDEF 0123 4567"
.parse::<Fingerprint>().unwrap());
}
}