use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CacheControl {
pub kind: CacheControlKind,
pub ttl: CacheTtl,
}
impl CacheControl {
#[must_use]
pub const fn ephemeral() -> Self {
Self {
kind: CacheControlKind::Ephemeral,
ttl: CacheTtl::FiveMinutes,
}
}
#[must_use]
pub const fn with_ttl(mut self, ttl: CacheTtl) -> Self {
self.ttl = ttl;
self
}
#[must_use]
pub const fn ttl_wire(&self) -> &'static str {
match self.ttl {
CacheTtl::FiveMinutes => "5m",
CacheTtl::OneHour => "1h",
}
}
}
impl Default for CacheControl {
fn default() -> Self {
Self::ephemeral()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CacheControlKind {
Ephemeral,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CacheTtl {
#[default]
FiveMinutes,
OneHour,
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn cache_control_default_is_ephemeral_five_minutes() {
let ctrl = CacheControl::default();
assert_eq!(ctrl.kind, CacheControlKind::Ephemeral);
assert_eq!(ctrl.ttl, CacheTtl::FiveMinutes);
}
#[test]
fn cache_control_with_ttl_overrides() {
let ctrl = CacheControl::ephemeral().with_ttl(CacheTtl::OneHour);
assert_eq!(ctrl.ttl, CacheTtl::OneHour);
}
#[test]
fn cache_control_ttl_wire_strings() {
assert_eq!(CacheControl::ephemeral().ttl_wire(), "5m");
assert_eq!(
CacheControl::ephemeral()
.with_ttl(CacheTtl::OneHour)
.ttl_wire(),
"1h"
);
}
}