1 // This is a part of Chrono.
2 // See README.md and LICENSE.txt for details.
3 
4 //! ISO 8601 week.
5 
6 use core::fmt;
7 
8 use super::internals::{DateImpl, Of, YearFlags};
9 
10 #[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
11 use rkyv::{Archive, Deserialize, Serialize};
12 
13 /// ISO 8601 week.
14 ///
15 /// This type, combined with [`Weekday`](../enum.Weekday.html),
16 /// constitutes the ISO 8601 [week date](./struct.NaiveDate.html#week-date).
17 /// One can retrieve this type from the existing [`Datelike`](../trait.Datelike.html) types
18 /// via the [`Datelike::iso_week`](../trait.Datelike.html#tymethod.iso_week) method.
19 #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Hash)]
20 #[cfg_attr(
21     any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
22     derive(Archive, Deserialize, Serialize),
23     archive(compare(PartialEq, PartialOrd)),
24     archive_attr(derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash))
25 )]
26 #[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
27 pub struct IsoWeek {
28     // note that this allows for larger year range than `NaiveDate`.
29     // this is crucial because we have an edge case for the first and last week supported,
30     // which year number might not match the calendar year number.
31     ywf: DateImpl, // (year << 10) | (week << 4) | flag
32 }
33 
34 /// Returns the corresponding `IsoWeek` from the year and the `Of` internal value.
35 //
36 // internal use only. we don't expose the public constructor for `IsoWeek` for now,
37 // because the year range for the week date and the calendar date do not match and
38 // it is confusing to have a date that is out of range in one and not in another.
39 // currently we sidestep this issue by making `IsoWeek` fully dependent of `Datelike`.
iso_week_from_yof(year: i32, of: Of) -> IsoWeek40 pub(super) fn iso_week_from_yof(year: i32, of: Of) -> IsoWeek {
41     let (rawweek, _) = of.isoweekdate_raw();
42     let (year, week) = if rawweek < 1 {
43         // previous year
44         let prevlastweek = YearFlags::from_year(year - 1).nisoweeks();
45         (year - 1, prevlastweek)
46     } else {
47         let lastweek = of.flags().nisoweeks();
48         if rawweek > lastweek {
49             // next year
50             (year + 1, 1)
51         } else {
52             (year, rawweek)
53         }
54     };
55     let flags = YearFlags::from_year(year);
56     IsoWeek { ywf: (year << 10) | (week << 4) as DateImpl | DateImpl::from(flags.0) }
57 }
58 
59 impl IsoWeek {
60     /// Returns the year number for this ISO week.
61     ///
62     /// # Example
63     ///
64     /// ```
65     /// use chrono::{NaiveDate, Datelike, Weekday};
66     ///
67     /// let d = NaiveDate::from_isoywd_opt(2015, 1, Weekday::Mon).unwrap();
68     /// assert_eq!(d.iso_week().year(), 2015);
69     /// ```
70     ///
71     /// This year number might not match the calendar year number.
72     /// Continuing the example...
73     ///
74     /// ```
75     /// # use chrono::{NaiveDate, Datelike, Weekday};
76     /// # let d = NaiveDate::from_isoywd_opt(2015, 1, Weekday::Mon).unwrap();
77     /// assert_eq!(d.year(), 2014);
78     /// assert_eq!(d, NaiveDate::from_ymd_opt(2014, 12, 29).unwrap());
79     /// ```
80     #[inline]
year(&self) -> i3281     pub const fn year(&self) -> i32 {
82         self.ywf >> 10
83     }
84 
85     /// Returns the ISO week number starting from 1.
86     ///
87     /// The return value ranges from 1 to 53. (The last week of year differs by years.)
88     ///
89     /// # Example
90     ///
91     /// ```
92     /// use chrono::{NaiveDate, Datelike, Weekday};
93     ///
94     /// let d = NaiveDate::from_isoywd_opt(2015, 15, Weekday::Mon).unwrap();
95     /// assert_eq!(d.iso_week().week(), 15);
96     /// ```
97     #[inline]
week(&self) -> u3298     pub const fn week(&self) -> u32 {
99         ((self.ywf >> 4) & 0x3f) as u32
100     }
101 
102     /// Returns the ISO week number starting from 0.
103     ///
104     /// The return value ranges from 0 to 52. (The last week of year differs by years.)
105     ///
106     /// # Example
107     ///
108     /// ```
109     /// use chrono::{NaiveDate, Datelike, Weekday};
110     ///
111     /// let d = NaiveDate::from_isoywd_opt(2015, 15, Weekday::Mon).unwrap();
112     /// assert_eq!(d.iso_week().week0(), 14);
113     /// ```
114     #[inline]
week0(&self) -> u32115     pub const fn week0(&self) -> u32 {
116         ((self.ywf >> 4) & 0x3f) as u32 - 1
117     }
118 }
119 
120 /// The `Debug` output of the ISO week `w` is the same as
121 /// [`d.format("%G-W%V")`](../format/strftime/index.html)
122 /// where `d` is any `NaiveDate` value in that week.
123 ///
124 /// # Example
125 ///
126 /// ```
127 /// use chrono::{NaiveDate, Datelike};
128 ///
129 /// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(2015,  9,  5).unwrap().iso_week()), "2015-W36");
130 /// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(   0,  1,  3).unwrap().iso_week()), "0000-W01");
131 /// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(9999, 12, 31).unwrap().iso_week()), "9999-W52");
132 /// ```
133 ///
134 /// ISO 8601 requires an explicit sign for years before 1 BCE or after 9999 CE.
135 ///
136 /// ```
137 /// # use chrono::{NaiveDate, Datelike};
138 /// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(    0,  1,  2).unwrap().iso_week()),  "-0001-W52");
139 /// assert_eq!(format!("{:?}", NaiveDate::from_ymd_opt(10000, 12, 31).unwrap().iso_week()), "+10000-W52");
140 /// ```
141 impl fmt::Debug for IsoWeek {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result142     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143         let year = self.year();
144         let week = self.week();
145         if (0..=9999).contains(&year) {
146             write!(f, "{:04}-W{:02}", year, week)
147         } else {
148             // ISO 8601 requires the explicit sign for out-of-range years
149             write!(f, "{:+05}-W{:02}", year, week)
150         }
151     }
152 }
153 
154 #[cfg(test)]
155 mod tests {
156     #[cfg(feature = "rkyv-validation")]
157     use super::IsoWeek;
158     use crate::naive::{internals, NaiveDate};
159     use crate::Datelike;
160 
161     #[test]
test_iso_week_extremes()162     fn test_iso_week_extremes() {
163         let minweek = NaiveDate::MIN.iso_week();
164         let maxweek = NaiveDate::MAX.iso_week();
165 
166         assert_eq!(minweek.year(), internals::MIN_YEAR);
167         assert_eq!(minweek.week(), 1);
168         assert_eq!(minweek.week0(), 0);
169         #[cfg(feature = "alloc")]
170         assert_eq!(format!("{:?}", minweek), NaiveDate::MIN.format("%G-W%V").to_string());
171 
172         assert_eq!(maxweek.year(), internals::MAX_YEAR + 1);
173         assert_eq!(maxweek.week(), 1);
174         assert_eq!(maxweek.week0(), 0);
175         #[cfg(feature = "alloc")]
176         assert_eq!(format!("{:?}", maxweek), NaiveDate::MAX.format("%G-W%V").to_string());
177     }
178 
179     #[test]
test_iso_week_equivalence_for_first_week()180     fn test_iso_week_equivalence_for_first_week() {
181         let monday = NaiveDate::from_ymd_opt(2024, 12, 30).unwrap();
182         let friday = NaiveDate::from_ymd_opt(2025, 1, 3).unwrap();
183 
184         assert_eq!(monday.iso_week(), friday.iso_week());
185     }
186 
187     #[test]
test_iso_week_equivalence_for_last_week()188     fn test_iso_week_equivalence_for_last_week() {
189         let monday = NaiveDate::from_ymd_opt(2026, 12, 28).unwrap();
190         let friday = NaiveDate::from_ymd_opt(2027, 1, 1).unwrap();
191 
192         assert_eq!(monday.iso_week(), friday.iso_week());
193     }
194 
195     #[test]
test_iso_week_ordering_for_first_week()196     fn test_iso_week_ordering_for_first_week() {
197         let monday = NaiveDate::from_ymd_opt(2024, 12, 30).unwrap();
198         let friday = NaiveDate::from_ymd_opt(2025, 1, 3).unwrap();
199 
200         assert!(monday.iso_week() >= friday.iso_week());
201         assert!(monday.iso_week() <= friday.iso_week());
202     }
203 
204     #[test]
test_iso_week_ordering_for_last_week()205     fn test_iso_week_ordering_for_last_week() {
206         let monday = NaiveDate::from_ymd_opt(2026, 12, 28).unwrap();
207         let friday = NaiveDate::from_ymd_opt(2027, 1, 1).unwrap();
208 
209         assert!(monday.iso_week() >= friday.iso_week());
210         assert!(monday.iso_week() <= friday.iso_week());
211     }
212 
213     #[test]
214     #[cfg(feature = "rkyv-validation")]
test_rkyv_validation()215     fn test_rkyv_validation() {
216         let minweek = NaiveDate::MIN.iso_week();
217         let bytes = rkyv::to_bytes::<_, 4>(&minweek).unwrap();
218         assert_eq!(rkyv::from_bytes::<IsoWeek>(&bytes).unwrap(), minweek);
219 
220         let maxweek = NaiveDate::MAX.iso_week();
221         let bytes = rkyv::to_bytes::<_, 4>(&maxweek).unwrap();
222         assert_eq!(rkyv::from_bytes::<IsoWeek>(&bytes).unwrap(), maxweek);
223     }
224 }
225