use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::error::NbError;
use crate::parser::NoteDocument;
const PREFIX: &str = "b3:";
const HEX_LEN: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Fingerprint(String);
impl Fingerprint {
pub fn from_json(s: &str) -> Result<Self, NbError> {
let inner: String = serde_json::from_str(s).map_err(|e| NbError::JsonParseError {
source: e.to_string(),
})?;
inner.parse()
}
pub fn as_hex(&self) -> &str {
&self.0
}
pub fn as_str(&self) -> String {
let mut buf = String::with_capacity(PREFIX.len() + self.0.len());
buf.push_str(PREFIX);
buf.push_str(&self.0);
buf
}
}
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(PREFIX)?;
f.write_str(&self.0)
}
}
impl FromStr for Fingerprint {
type Err = NbError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate(s)?;
Ok(Fingerprint(s[PREFIX.len()..].to_ascii_lowercase()))
}
}
fn validate(s: &str) -> Result<(), NbError> {
if s.is_empty() {
return Err(NbError::InvalidFingerprint {
reason: "empty".to_string(),
});
}
if s.starts_with(|c: char| c.is_whitespace()) {
return Err(NbError::InvalidFingerprint {
reason: "leading_whitespace".to_string(),
});
}
if s.ends_with(|c: char| c.is_whitespace()) {
return Err(NbError::InvalidFingerprint {
reason: "trailing_whitespace".to_string(),
});
}
if !s.starts_with(PREFIX) {
return Err(NbError::InvalidFingerprint {
reason: "unknown_algorithm_prefix".to_string(),
});
}
let hex = &s[PREFIX.len()..];
if hex.len() != HEX_LEN {
return Err(NbError::InvalidFingerprint {
reason: "wrong_length".to_string(),
});
}
for c in hex.chars() {
if !c.is_ascii_hexdigit() {
return Err(NbError::InvalidFingerprint {
reason: "invalid_hex".to_string(),
});
}
if c.is_ascii_uppercase() {
return Err(NbError::InvalidFingerprint {
reason: "uppercase_hex".to_string(),
});
}
}
Ok(())
}
impl Serialize for Fingerprint {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&format!("{PREFIX}{}", self.0))
}
}
impl<'de> Deserialize<'de> for Fingerprint {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Fingerprint {
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("Fingerprint")
}
fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"pattern": "^b3:[0-9a-f]{64}$"
})
}
}
pub fn fingerprint(doc: &NoteDocument) -> Fingerprint {
let mut hasher = blake3::Hasher::new();
for fragment in doc.body() {
hasher.update(fragment);
}
let hash = hasher.finalize();
let hex = hash.to_hex(); Fingerprint(hex.to_string())
}