use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use crate::encoding;
pub const OPERATION_ID_MAX_LEN: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseIdError {
#[error("expected {expected} lowercase hex digits")]
InvalidHex {
expected: usize,
},
#[error("operation id is empty")]
Empty,
#[error("operation id is longer than {OPERATION_ID_MAX_LEN} characters")]
TooLong,
#[error("operation id may contain only A-Z, a-z, 0-9, '_' and '-'")]
InvalidCharacter,
}
macro_rules! hex_bytes_type {
($name:ident, $len:literal) => {
impl $name {
pub const fn from_bytes(bytes: [u8; $len]) -> Self {
Self(bytes)
}
pub const fn as_bytes(&self) -> &[u8; $len] {
&self.0
}
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
}
impl From<[u8; $len]> for $name {
fn from(bytes: [u8; $len]) -> Self {
Self(bytes)
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, concat!(stringify!($name), "({})"), self.to_hex())
}
}
impl FromStr for $name {
type Err = ParseIdError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
encoding::decode_lower_hex::<$len>(text)
.map(Self)
.ok_or(ParseIdError::InvalidHex { expected: $len * 2 })
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
};
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EventId([u8; 32]);
hex_bytes_type!(EventId, 32);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Sha256Digest([u8; 32]);
hex_bytes_type!(Sha256Digest, 32);
impl Sha256Digest {
pub fn of(data: &[u8]) -> Self {
Self(Sha256::digest(data).into())
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChallengeId([u8; 16]);
hex_bytes_type!(ChallengeId, 16);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InvitationId([u8; 16]);
hex_bytes_type!(InvitationId, 16);
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct Revision(u64);
impl Revision {
pub const fn new(value: u64) -> Self {
Self(value)
}
pub const fn get(self) -> u64 {
self.0
}
pub const fn next(self) -> Option<Self> {
match self.0.checked_add(1) {
Some(value) => Some(Self(value)),
None => None,
}
}
}
impl From<u64> for Revision {
fn from(value: u64) -> Self {
Self(value)
}
}
impl From<Revision> for u64 {
fn from(revision: Revision) -> Self {
revision.0
}
}
impl fmt::Display for Revision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct UnixTime(u64);
impl UnixTime {
pub const fn from_secs(secs: u64) -> Self {
Self(secs)
}
pub const fn as_secs(self) -> u64 {
self.0
}
pub const fn checked_add(self, duration: Duration) -> Option<Self> {
match self.0.checked_add(duration.as_secs()) {
Some(secs) => Some(Self(secs)),
None => None,
}
}
pub const fn abs_diff(self, other: Self) -> u64 {
self.0.abs_diff(other.0)
}
}
impl From<u64> for UnixTime {
fn from(secs: u64) -> Self {
Self(secs)
}
}
impl From<UnixTime> for u64 {
fn from(time: UnixTime) -> Self {
time.0
}
}
impl fmt::Display for UnixTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OperationId(String);
impl OperationId {
pub fn as_str(&self) -> &str {
&self.0
}
fn validate(text: &str) -> Result<(), ParseIdError> {
if text.is_empty() {
return Err(ParseIdError::Empty);
}
if text.len() > OPERATION_ID_MAX_LEN {
return Err(ParseIdError::TooLong);
}
if !text
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return Err(ParseIdError::InvalidCharacter);
}
Ok(())
}
}
impl FromStr for OperationId {
type Err = ParseIdError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::validate(text)?;
Ok(Self(text.to_owned()))
}
}
impl TryFrom<String> for OperationId {
type Error = ParseIdError;
fn try_from(text: String) -> Result<Self, Self::Error> {
Self::validate(&text)?;
Ok(Self(text))
}
}
impl AsRef<str> for OperationId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for OperationId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl Serialize for OperationId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for OperationId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
Self::try_from(text).map_err(serde::de::Error::custom)
}
}