You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
yuurei/src/tripcode.rs

110 lines
2.3 KiB

//! Tripcode. TODO: Use kana-hash
use super::*;
use khash::{
ctx::{
self,
Algorithm,
},
salt,
};
use std::{
fmt,
error,
};
#[derive(Debug)]
pub struct Error(khash::error::Error);
impl From<khash::error::Error> for Error
{
#[inline] fn from(from: khash::error::Error) -> Self
{
Self(from)
}
}
impl fmt::Display for Error
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
write!(f, "failed to compute tripcode")
}
}
impl error::Error for Error
{
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(&self.0)
}
}
///A kana-hash or special tripcode
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[derive(Serialize, Deserialize)]
pub enum Tripcode
{
/// A secure tripcode computed with the user set configured salt
Secure(String),
/// A normal tripcode computed with the default embedded salt
Normal(String),
/// A special tripcode with a pre-set string
Special(String),
}
impl Tripcode
{
/// Generate a new normal tripcode
pub fn new_normal(from: impl AsRef<[u8]>) -> Result<Self, Error>
{
Ok(Self::Normal(khash::generate(&ctx::Context::new(Algorithm::Sha256Truncated, salt::Salt::internal()), from)?))
}
/// Generate a new `secure' tripcode.
///
/// # Panics
/// If global config has not been set yet.
pub fn new_secure(from: impl AsRef<[u8]>) -> Result<Self, Error>
{
Ok(Self::Secure(khash::generate(&ctx::Context::new(Algorithm::Sha256Truncated, salt::Salt::fixed(config::get().tripcode_salt)), from)?))
}
/// Get the internal string representing the tripcode.
///
/// # Notes
/// This does not include the prefixes.
pub fn as_str(&self) -> &str
{
match self {
Self::Secure(s) | Self::Normal(s) | Self::Special(s) => s.as_str()
}
}
/// Consume the instance returning the inner string.
///
/// # Notes
/// This does not include the prefixes.
pub fn into_inner(self) -> String
{
match self {
Self::Secure(s) | Self::Normal(s) | Self::Special(s) => s
}
}
}
impl fmt::Display for Tripcode
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
match self {
Self::Secure(sec) => write!(f, "!!{}", sec),
Self::Normal(nor) => write!(f, "!{}", nor),
Self::Special(spec) => write!(f, "{}", spec),
}
}
}