use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CacheTtl {
#[default]
FiveMinutes,
OneHour,
}
impl CacheTtl {
#[must_use]
pub const fn wire_ttl_field(self) -> Option<&'static str> {
match self {
Self::FiveMinutes => None,
Self::OneHour => Some("1h"),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CacheControl {
pub ttl: CacheTtl,
}
impl CacheControl {
#[must_use]
pub const fn five_minutes() -> Self {
Self {
ttl: CacheTtl::FiveMinutes,
}
}
#[must_use]
pub const fn one_hour() -> Self {
Self {
ttl: CacheTtl::OneHour,
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn wire_ttl_field_is_stable() {
assert_eq!(CacheTtl::FiveMinutes.wire_ttl_field(), None);
assert_eq!(CacheTtl::OneHour.wire_ttl_field(), Some("1h"));
}
#[test]
fn const_constructors_match_variants() {
assert_eq!(CacheControl::five_minutes().ttl, CacheTtl::FiveMinutes);
assert_eq!(CacheControl::one_hour().ttl, CacheTtl::OneHour);
}
#[test]
fn cache_control_round_trips_via_serde() {
let cc = CacheControl::one_hour();
let json = serde_json::to_string(&cc).unwrap();
let back: CacheControl = serde_json::from_str(&json).unwrap();
assert_eq!(cc, back);
}
}