use std::{fmt, str::FromStr, time::Duration};
use const_macros::{const_early, const_ok, const_try};
use miette::Diagnostic;
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use crate::{int, macros::errors};
pub const MIN: u64 = 1;
pub const DEFAULT: u64 = 30;
#[derive(Debug, Error, Diagnostic)]
#[error("expected period to be at least `{MIN}`, got `{value}`")]
#[diagnostic(
code(otp_std::period),
help("make sure the period is at least `{MIN}`")
)]
pub struct Error {
pub value: u64,
}
impl Error {
pub const fn new(value: u64) -> Self {
Self { value }
}
}
#[derive(Debug, Error, Diagnostic)]
#[error(transparent)]
#[diagnostic(transparent)]
pub enum ParseErrorSource {
Period(#[from] Error),
Int(#[from] int::ParseError),
}
#[derive(Debug, Error, Diagnostic)]
#[error("failed to parse `{string}` to digits")]
#[diagnostic(
code(otp_std::period::parse),
help("see the report for more information")
)]
pub struct ParseError {
#[source]
#[diagnostic_source]
pub source: ParseErrorSource,
pub string: String,
}
impl ParseError {
pub const fn new(source: ParseErrorSource, string: String) -> Self {
Self { source, string }
}
pub fn period(error: Error, string: String) -> Self {
Self::new(error.into(), string)
}
pub fn int(error: int::ParseError, string: String) -> Self {
Self::new(error.into(), string)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Period {
value: u64,
}
#[cfg(feature = "serde")]
impl Serialize for Period {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.get().serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Period {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = u64::deserialize(deserializer)?;
Self::new(value).map_err(de::Error::custom)
}
}
errors! {
Type = ParseError,
Hack = $,
int_error => int(error, string => to_owned),
period_error => period(error, string => to_owned),
}
impl FromStr for Period {
type Err = ParseError;
fn from_str(string: &str) -> Result<Self, Self::Err> {
let value = string
.parse()
.map_err(|error| int_error!(int::wrap(error), string))?;
Self::new(value).map_err(|error| period_error!(error, string))
}
}
impl fmt::Display for Period {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.get().fmt(formatter)
}
}
impl TryFrom<u64> for Period {
type Error = Error;
fn try_from(value: u64) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<Period> for u64 {
fn from(period: Period) -> Self {
period.get()
}
}
impl Default for Period {
fn default() -> Self {
Self::DEFAULT
}
}
errors! {
Type = Error,
Hack = $,
error => new(value),
}
impl Period {
pub const fn new(value: u64) -> Result<Self, Error> {
const_try!(Self::check(value));
Ok(unsafe { Self::new_unchecked(value) })
}
pub const fn new_ok(value: u64) -> Option<Self> {
const_ok!(Self::new(value))
}
pub const fn check(value: u64) -> Result<(), Error> {
const_early!(value < MIN => error!(value));
Ok(())
}
pub const unsafe fn new_unchecked(value: u64) -> Self {
Self { value }
}
pub const fn get(self) -> u64 {
self.value
}
pub const fn as_duration(self) -> Duration {
Duration::from_secs(self.get())
}
pub const MIN: Self = Self::new_ok(MIN).unwrap();
pub const DEFAULT: Self = Self::new_ok(DEFAULT).unwrap();
}