Skip to main content

soml/
date.rs

1use crate::Error;
2use std::fmt::{self, Display};
3use std::str::FromStr;
4
5/**
6A calendar date in the proleptic Gregorian calendar, from `0001-01-01` to `9999-12-31`. It has no timezone, time of day, or duration, and its components never pass through an instant.
7
8With serde, it reads only from a native SOML date, not from a string, and it is written as a native date. Other formats, including JSON, see its exact `YYYY-MM-DD` text.
9
10```rust
11let date = soml::Date::new(1582, 10, 10).unwrap();
12assert_eq!(date.to_string(), "1582-10-10");
13assert_eq!((date.year(), date.month(), date.day()), (1582, 10, 10));
14```
15*/
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Date {
18	year: u16,
19	month: u8,
20	day: u8,
21}
22
23/**
24The name that tells the SOML serializer and deserializer that a newtype struct is a date. Other formats treat a newtype struct as its content, so they see the canonical text.
25*/
26pub(crate) const TOKEN: &str = "$soml::Date";
27
28impl Date {
29	/**
30	Creates a date from Gregorian components. Returns `None` for a year outside 1 through 9999, or a month or day that does not exist.
31	*/
32	#[must_use]
33	pub fn new(year: u16, month: u8, day: u8) -> Option<Self> {
34		Self::calendar_error(u32::from(year), u32::from(month), u32::from(day))
35			.is_none()
36			.then_some(Self { year, month, day })
37	}
38
39	/**
40	The year, from 1 through 9999.
41	*/
42	#[must_use]
43	pub const fn year(self) -> u16 {
44		self.year
45	}
46
47	/**
48	The month, from 1 through 12.
49	*/
50	#[must_use]
51	pub const fn month(self) -> u8 {
52		self.month
53	}
54
55	/**
56	The day, from 1 through the last day of its month.
57	*/
58	#[must_use]
59	pub const fn day(self) -> u8 {
60		self.day
61	}
62
63	/**
64	Reads exact ASCII date text, without accepting the date prefix of a longer token.
65	*/
66	pub(crate) fn parse(text: &str) -> Result<Self, String> {
67		let bytes = text.as_bytes();
68		if bytes.len() != 10 || !crate::scalar::has_date_prefix(bytes) {
69			return Err(format!(
70				"Invalid date “{}”. A date is written as YYYY-MM-DD",
71				crate::abbreviate(text, 40)
72			));
73		}
74		let year = u32::from(bytes[0] - b'0') * 1000
75			+ u32::from(bytes[1] - b'0') * 100
76			+ u32::from(bytes[2] - b'0') * 10
77			+ u32::from(bytes[3] - b'0');
78		let month = u32::from(bytes[5] - b'0') * 10 + u32::from(bytes[6] - b'0');
79		let day = u32::from(bytes[8] - b'0') * 10 + u32::from(bytes[9] - b'0');
80		if let Some(problem) = Self::calendar_error(year, month, day) {
81			return Err(format!("Invalid date {text}: {problem}"));
82		}
83		Ok(Self {
84			year: year as u16,
85			month: month as u8,
86			day: day as u8,
87		})
88	}
89
90	/**
91	The first invalid Gregorian component, with a reason, or `None` when the date exists in the proleptic Gregorian calendar. Shared with instant validation.
92	*/
93	pub(crate) fn calendar_error(year: u32, month: u32, day: u32) -> Option<String> {
94		if !(1..=9999).contains(&year) {
95			return Some("the year must be 0001 to 9999".to_owned());
96		}
97		if !(1..=12).contains(&month) {
98			return Some("the month must be 01 to 12".to_owned());
99		}
100		let last_day = Self::days_in_month(year, month);
101		if day < 1 || day > last_day {
102			return Some(format!("the day must be 01 to {last_day} in that month"));
103		}
104		None
105	}
106
107	/**
108	The length of a month from 1 through 12 in the proleptic Gregorian calendar.
109	*/
110	const fn days_in_month(year: u32, month: u32) -> u32 {
111		let is_leap_year =
112			year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
113		match month {
114			2 if is_leap_year => 29,
115			2 => 28,
116			4 | 6 | 9 | 11 => 30,
117			_ => 31,
118		}
119	}
120}
121
122/**
123Writes the canonical form, `YYYY-MM-DD`.
124*/
125impl Display for Date {
126	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127		let mut text = *b"0000-00-00";
128		crate::instant::put_digits(&mut text[..4], u32::from(self.year));
129		crate::instant::put_digits(&mut text[5..7], u32::from(self.month));
130		crate::instant::put_digits(&mut text[8..], u32::from(self.day));
131		formatter.write_str(std::str::from_utf8(&text).expect("the digits are ASCII"))
132	}
133}
134
135impl fmt::Debug for Date {
136	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137		write!(formatter, "Date({self})")
138	}
139}
140
141/**
142Reads an exact `YYYY-MM-DD` date, rejecting impossible components.
143
144```rust
145let date: soml::Date = "1582-10-10".parse()?;
146assert_eq!(date.to_string(), "1582-10-10");
147
148assert!("2026-02-30".parse::<soml::Date>().is_err());
149# Ok::<(), soml::Error>(())
150```
151*/
152impl FromStr for Date {
153	type Err = Error;
154
155	fn from_str(text: &str) -> Result<Self, Error> {
156		Self::parse(text).map_err(Error::syntax)
157	}
158}
159
160serde_temporal_scalar!(Date, "a date");