cookie_monster/cookie/expires/
dep_time.rs1use time::{
2 Duration, OffsetDateTime, UtcOffset, format_description::FormatItem, macros::format_description,
3};
4
5use crate::{Cookie, cookie::expires::ExpVal};
6
7use super::Expires;
8
9static FMT: &[FormatItem<'_>] = format_description!(
10 "[weekday repr:short], [day] [month repr:short] [year padding:none] [hour]:[minute]:[second] GMT"
11);
12
13impl From<OffsetDateTime> for Expires {
14 fn from(value: OffsetDateTime) -> Self {
15 Self::Exp(ExpVal {
16 time: Some(value),
17 ..Default::default()
18 })
19 }
20}
21
22impl Cookie {
23 pub fn expires_time(&self) -> Option<OffsetDateTime> {
25 match &self.expires {
26 Expires::Exp(ExpVal { time, .. }) => *time,
27 _ => None,
28 }
29 }
30
31 pub fn max_age_time(&self) -> Option<Duration> {
33 self.max_age_secs()
34 .map(|max_age| Duration::seconds(max_age as i64))
35 }
36}
37
38impl Expires {
39 pub fn remove_time() -> Self {
41 Self::from(OffsetDateTime::now_utc() - Duration::days(365))
42 }
43}
44
45pub(super) fn ser_expires(expires: &OffsetDateTime, buf: &mut String) -> crate::Result<()> {
46 let expires = expires
47 .to_offset(UtcOffset::UTC)
48 .format(&FMT)
49 .map_err(|_| crate::Error::ExpiresFmt)?;
50
51 buf.push_str("; Expires=");
52 buf.push_str(&expires);
53
54 Ok(())
55}
56
57#[cfg(test)]
58mod test_time {
59 use crate::Cookie;
60 use time::macros::datetime;
61
62 #[test]
63 fn parse() {
64 let expires = datetime!(2015-10-21 7:28:0 UTC);
65
66 let expected = Cookie::build("foo", "bar").expires(expires).build();
67
68 assert_eq!(
69 expected.serialize().as_deref(),
70 Ok("foo=bar; Expires=Wed, 21 Oct 2015 07:28:00 GMT")
71 )
72 }
73}