use std::fmt;
use sha2::{Digest, Sha256};
use thiserror::Error;
#[derive(Clone, PartialEq, Eq)]
pub struct InvitationCode([u8; 32]);
impl InvitationCode {
pub fn new(code: &str) -> Result<Self, InvalidInvitationCode> {
if code.is_empty() {
return Err(InvalidInvitationCode);
}
Ok(Self(Sha256::digest(code.as_bytes()).into()))
}
pub fn from_digest(digest: [u8; 32]) -> Self {
Self(digest)
}
pub fn from_hex_digest(value: &str) -> Result<Self, hex::FromHexError> {
let mut digest = [0; 32];
hex::decode_to_slice(value, &mut digest)?;
Ok(Self::from_digest(digest))
}
pub fn to_hex_digest(&self) -> String {
hex::encode(self.0)
}
pub(crate) fn digest(&self) -> &[u8] {
&self.0
}
}
impl fmt::Debug for InvitationCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("InvitationCode([REDACTED])")
}
}
#[derive(Debug, Error, PartialEq, Eq)]
#[error("invitation code must not be empty")]
pub struct InvalidInvitationCode;