|
| 1 | +use std::fmt::Display; |
| 2 | +use std::str::FromStr; |
| 3 | +use std::time::Duration; |
| 4 | + |
| 5 | +#[derive(thiserror::Error, Debug)] |
| 6 | +pub enum Error { |
| 7 | + #[error("expiration value is empty")] |
| 8 | + Empty, |
| 9 | + #[error("failed to parse number: {0}")] |
| 10 | + ParsingNumber(std::num::ParseIntError), |
| 11 | + #[error("illegal modifier, only =d allowed")] |
| 12 | + IllegalModifier, |
| 13 | + #[error("multiple default values")] |
| 14 | + MultipleDefaults, |
| 15 | +} |
| 16 | + |
| 17 | +/// Single expiration value that can be the default in a set of values. |
| 18 | +#[derive(Ord, Eq, PartialEq, PartialOrd)] |
| 19 | +pub struct Expiration { |
| 20 | + pub duration: Duration, |
| 21 | + pub default: bool, |
| 22 | +} |
| 23 | + |
| 24 | +/// Multiple expiration values in ordered fashion. |
| 25 | +pub struct ExpirationSet(Vec<Expiration>); |
| 26 | + |
| 27 | +/// A single [`Expiration`] can either be an unsigned number or an unsigned number followed by `=d` |
| 28 | +/// to denote a default expiration. |
| 29 | +impl FromStr for Expiration { |
| 30 | + type Err = Error; |
| 31 | + |
| 32 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 33 | + let mut parts = s.split('='); |
| 34 | + |
| 35 | + let Some(secs) = parts.next() else { |
| 36 | + return Err(Error::Empty); |
| 37 | + }; |
| 38 | + |
| 39 | + let secs = secs.parse::<u64>().map_err(Error::ParsingNumber)?; |
| 40 | + |
| 41 | + let default = parts.next().map_or(Ok(false), |p| { |
| 42 | + if p == "d" { |
| 43 | + Ok(true) |
| 44 | + } else { |
| 45 | + Err(Error::IllegalModifier) |
| 46 | + } |
| 47 | + })?; |
| 48 | + |
| 49 | + Ok(Self { |
| 50 | + duration: Duration::from_secs(secs), |
| 51 | + default, |
| 52 | + }) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +/// Print human-readable duration in a very rough approximation. |
| 57 | +impl Display for Expiration { |
| 58 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 59 | + /// Computes `dividend` / `divisor` and returns `Some(fraction)` if > 0. |
| 60 | + fn div(dividend: u64, divisor: u64) -> Option<(u64, u64)> { |
| 61 | + let r = dividend / divisor; |
| 62 | + (r > 0).then_some((r, dividend % divisor)) |
| 63 | + } |
| 64 | + |
| 65 | + let mut secs = self.duration.as_secs(); |
| 66 | + |
| 67 | + if secs == 0 { |
| 68 | + return write!(f, "never"); |
| 69 | + } |
| 70 | + |
| 71 | + if let Some((years, rem)) = div(secs, 60 * 60 * 24 * 7 * 4 * 12) { |
| 72 | + if years > 1 { |
| 73 | + write!(f, "{years} years")?; |
| 74 | + } else { |
| 75 | + write!(f, "{years} year")?; |
| 76 | + } |
| 77 | + secs = rem; |
| 78 | + } |
| 79 | + |
| 80 | + if let Some((months, rem)) = div(secs, 60 * 60 * 24 * 7 * 4) { |
| 81 | + if months > 1 { |
| 82 | + write!(f, "{months} months")?; |
| 83 | + } else { |
| 84 | + write!(f, "{months} month")?; |
| 85 | + } |
| 86 | + secs = rem; |
| 87 | + } |
| 88 | + |
| 89 | + if let Some((weeks, rem)) = div(secs, 60 * 60 * 24 * 7) { |
| 90 | + if weeks > 1 { |
| 91 | + write!(f, "{weeks} weeks")?; |
| 92 | + } else { |
| 93 | + write!(f, "{weeks} week")?; |
| 94 | + } |
| 95 | + secs = rem; |
| 96 | + } |
| 97 | + |
| 98 | + if let Some((days, rem)) = div(secs, 60 * 60 * 24) { |
| 99 | + if days > 1 { |
| 100 | + write!(f, "{days} days")?; |
| 101 | + } else { |
| 102 | + write!(f, "{days} day")?; |
| 103 | + } |
| 104 | + secs = rem; |
| 105 | + } |
| 106 | + |
| 107 | + if let Some((hours, rem)) = div(secs, 60 * 60) { |
| 108 | + if hours > 1 { |
| 109 | + write!(f, "{hours} hours")?; |
| 110 | + } else { |
| 111 | + write!(f, "{hours} hour")?; |
| 112 | + } |
| 113 | + secs = rem; |
| 114 | + } |
| 115 | + |
| 116 | + if let Some((minutes, rem)) = div(secs, 60) { |
| 117 | + if minutes > 1 { |
| 118 | + write!(f, "{minutes} minutes")?; |
| 119 | + } else { |
| 120 | + write!(f, "{minutes} minute")?; |
| 121 | + } |
| 122 | + secs = rem; |
| 123 | + } |
| 124 | + |
| 125 | + if secs > 0 { |
| 126 | + write!(f, "{secs} seconds")?; |
| 127 | + } |
| 128 | + |
| 129 | + Ok(()) |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +impl FromStr for ExpirationSet { |
| 134 | + type Err = Error; |
| 135 | + |
| 136 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 137 | + let mut values: Vec<Expiration> = s |
| 138 | + .split(',') |
| 139 | + .map(FromStr::from_str) |
| 140 | + .collect::<Result<_, _>>()?; |
| 141 | + |
| 142 | + if values.iter().map(|exp| u64::from(exp.default)).sum::<u64>() > 1 { |
| 143 | + return Err(Error::MultipleDefaults); |
| 144 | + } |
| 145 | + |
| 146 | + values.sort(); |
| 147 | + |
| 148 | + Ok(ExpirationSet(values)) |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +impl ExpirationSet { |
| 153 | + /// Retrieve sorted vector of [`Expiration`] values. |
| 154 | + pub fn into_inner(self) -> Vec<Expiration> { |
| 155 | + self.0 |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +#[cfg(test)] |
| 160 | +mod tests { |
| 161 | + use super::*; |
| 162 | + |
| 163 | + impl Expiration { |
| 164 | + fn from_secs(secs: u64) -> Self { |
| 165 | + Self { |
| 166 | + duration: Duration::from_secs(secs), |
| 167 | + default: false, |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + #[test] |
| 173 | + fn non_default_expiration() { |
| 174 | + let expiration = "60".parse::<Expiration>().unwrap(); |
| 175 | + assert_eq!(expiration.duration, Duration::from_secs(60)); |
| 176 | + assert!(!expiration.default); |
| 177 | + } |
| 178 | + |
| 179 | + #[test] |
| 180 | + fn default_expiration() { |
| 181 | + let expiration = "60=d".parse::<Expiration>().unwrap(); |
| 182 | + assert_eq!(expiration.duration, Duration::from_secs(60)); |
| 183 | + assert!(expiration.default); |
| 184 | + } |
| 185 | + |
| 186 | + #[test] |
| 187 | + fn expiration_set() { |
| 188 | + let expirations = "3600,60=d,48000" |
| 189 | + .parse::<ExpirationSet>() |
| 190 | + .unwrap() |
| 191 | + .into_inner(); |
| 192 | + |
| 193 | + assert_eq!(expirations.len(), 3); |
| 194 | + |
| 195 | + assert_eq!(expirations[0].duration, Duration::from_secs(60)); |
| 196 | + assert_eq!(expirations[1].duration, Duration::from_secs(3600)); |
| 197 | + assert_eq!(expirations[2].duration, Duration::from_secs(48000)); |
| 198 | + |
| 199 | + assert!(expirations[0].default); |
| 200 | + assert!(!expirations[1].default); |
| 201 | + assert!(!expirations[2].default); |
| 202 | + } |
| 203 | + |
| 204 | + #[test] |
| 205 | + fn multiple_defaults() { |
| 206 | + assert!("3600=d,60=d,48000".parse::<ExpirationSet>().is_err()); |
| 207 | + } |
| 208 | + |
| 209 | + #[test] |
| 210 | + fn formatting() { |
| 211 | + assert_eq!(format!("{}", Expiration::from_secs(30)), "30 seconds"); |
| 212 | + assert_eq!(format!("{}", Expiration::from_secs(60)), "1 minute"); |
| 213 | + assert_eq!(format!("{}", Expiration::from_secs(60 * 2)), "2 minutes"); |
| 214 | + assert_eq!(format!("{}", Expiration::from_secs(60 * 60)), "1 hour"); |
| 215 | + assert_eq!(format!("{}", Expiration::from_secs(60 * 60 * 2)), "2 hours"); |
| 216 | + assert_eq!(format!("{}", Expiration::from_secs(60 * 60 * 24)), "1 day"); |
| 217 | + assert_eq!( |
| 218 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 2)), |
| 219 | + "2 days" |
| 220 | + ); |
| 221 | + assert_eq!( |
| 222 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 7)), |
| 223 | + "1 week" |
| 224 | + ); |
| 225 | + assert_eq!( |
| 226 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 7 * 2)), |
| 227 | + "2 weeks" |
| 228 | + ); |
| 229 | + assert_eq!( |
| 230 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 7 * 4)), |
| 231 | + "1 month" |
| 232 | + ); |
| 233 | + assert_eq!( |
| 234 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 7 * 8)), |
| 235 | + "2 months" |
| 236 | + ); |
| 237 | + assert_eq!( |
| 238 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 7 * 4 * 12)), |
| 239 | + "1 year" |
| 240 | + ); |
| 241 | + assert_eq!( |
| 242 | + format!("{}", Expiration::from_secs(60 * 60 * 24 * 7 * 4 * 24)), |
| 243 | + "2 years" |
| 244 | + ); |
| 245 | + } |
| 246 | +} |
0 commit comments