use std::error::Error;
use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ParseProjectIdError {
InvalidValue,
EmptyValue,
}
impl fmt::Display for ParseProjectIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseProjectIdError::InvalidValue => f.write_str("invalid value for project id"),
ParseProjectIdError::EmptyValue => f.write_str("empty or missing project id"),
}
}
}
impl Error for ParseProjectIdError {}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct ProjectId(u64);
impl ProjectId {
#[inline]
pub fn new(id: u64) -> Self {
Self(id)
}
#[inline]
pub fn value(self) -> u64 {
self.0
}
}
impl fmt::Display for ProjectId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value())
}
}
impl FromStr for ProjectId {
type Err = ParseProjectIdError;
fn from_str(s: &str) -> Result<ProjectId, ParseProjectIdError> {
if s.is_empty() {
return Err(ParseProjectIdError::EmptyValue);
}
match s.parse::<u64>() {
Ok(val) => Ok(ProjectId::new(val)),
Err(_) => Err(ParseProjectIdError::InvalidValue),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct ParseProjectKeyError;
impl fmt::Display for ParseProjectKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid project key")
}
}
impl std::error::Error for ParseProjectKeyError {}
#[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
pub struct ProjectKey([u8; 32]);
relay_common::impl_str_serde!(ProjectKey, "a project key string");
impl ProjectKey {
pub fn parse(key: &str) -> Result<Self, ParseProjectKeyError> {
if key.len() != 32 || !key.is_ascii() {
return Err(ParseProjectKeyError);
}
let mut project_key = Self(Default::default());
project_key.0.copy_from_slice(key.as_bytes());
Ok(project_key)
}
pub fn parse_with_flags(key: &str) -> Result<(Self, Vec<&str>), ParseProjectKeyError> {
let mut iter = key.split('.');
let key = ProjectKey::parse(iter.next().ok_or(ParseProjectKeyError)?)?;
Ok((key, iter.collect()))
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
#[inline]
pub fn as_str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.0) }
}
}
impl fmt::Debug for ProjectKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ProjectKey(\"{}\")", self.as_str())
}
}
impl fmt::Display for ProjectKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_str().fmt(f)
}
}
impl FromStr for ProjectKey {
type Err = ParseProjectKeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}