mirror of
https://github.com/chatmail/core.git
synced 2026-05-10 10:26:30 +03:00
refactor: Make Fingerprint not implement Display (#8177)
Currently, the Fingerprint type implements Display, but this doesn't get you the canonical fingerprint representation, but something human-readable. This is confusing, and back when I first used `Fingerprint`, I immediately wrote a bug because of this. So, instead, make a function `human_readable()` on Fingerprint. This comes from the discussion at https://github.com/chatmail/core/pull/8174#discussion_r3143130722.
This commit is contained in:
35
src/key.rs
35
src/key.rs
@@ -1,7 +1,7 @@
|
||||
//! Cryptographic key module.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::fmt::{self, Write as _};
|
||||
use std::io::Cursor;
|
||||
|
||||
use anyhow::{Context as _, Result, bail, ensure};
|
||||
@@ -583,6 +583,21 @@ impl Fingerprint {
|
||||
pub fn hex(&self) -> String {
|
||||
hex::encode_upper(&self.0)
|
||||
}
|
||||
|
||||
/// Make a human-readable fingerprint.
|
||||
pub fn human_readable(&self) -> String {
|
||||
let mut f = String::new();
|
||||
// Split key into chunks of 4 with space and newline at 20 chars
|
||||
for (i, c) in self.hex().chars().enumerate() {
|
||||
if i > 0 && i % 20 == 0 {
|
||||
writeln!(&mut f).ok();
|
||||
} else if i > 0 && i % 4 == 0 {
|
||||
write!(&mut f, " ").ok();
|
||||
}
|
||||
write!(&mut f, "{c}").ok();
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pgp::types::Fingerprint> for Fingerprint {
|
||||
@@ -599,22 +614,6 @@ impl fmt::Debug for Fingerprint {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a human-readable fingerprint.
|
||||
impl fmt::Display for Fingerprint {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// Split key into chunks of 4 with space and newline at 20 chars
|
||||
for (i, c) in self.hex().chars().enumerate() {
|
||||
if i > 0 && i % 20 == 0 {
|
||||
writeln!(f)?;
|
||||
} else if i > 0 && i % 4 == 0 {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
write!(f, "{c}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a human-readable or otherwise formatted fingerprint.
|
||||
impl std::str::FromStr for Fingerprint {
|
||||
type Err = anyhow::Error;
|
||||
@@ -890,7 +889,7 @@ i8pcjGO+IZffvyZJVRWfVooBJmWWbPB1pueo3tx8w3+fcuzpxz+RLFKaPyqXO+dD
|
||||
1, 2, 4, 8, 16, 32, 64, 128, 255, 1, 2, 4, 8, 16, 32, 64, 128, 255, 19, 20,
|
||||
]);
|
||||
assert_eq!(
|
||||
fp.to_string(),
|
||||
fp.human_readable(),
|
||||
"0102 0408 1020 4080 FF01\n0204 0810 2040 80FF 1314"
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user