Skip to main content

ifc_schedule/authoring/
datetime.rs

1//! Date and time values, in the form each release declares (#214).
2//!
3//! IFC4 and IFC4X3 declare `IfcWorkControl.CreationDate`, `StartTime` and
4//! `FinishTime` as `IfcDateTime`, an ISO 8601 string. IFC2X3 TC1 declares
5//! them `IfcDateTimeSelect`, a SELECT of three entities:
6//!
7//! ```text
8//! TYPE IfcDateTimeSelect = SELECT (IfcCalendarDate, IfcLocalTime, IfcDateAndTime);
9//! ENTITY IfcCalendarDate;  DayComponent, MonthComponent, YearComponent
10//! ENTITY IfcLocalTime;     HourComponent, MinuteComponent (OPTIONAL),
11//!                          SecondComponent (OPTIONAL), Zone (OPTIONAL),
12//!                          DaylightSavingOffset (OPTIONAL)
13//! ENTITY IfcDateAndTime;   DateComponent, TimeComponent
14//! ```
15//!
16//! [`DateTimeValue`] carries either form. The text form is written as given;
17//! a record form is checked against the schema's own rules
18//! (`IfcValidCalendarDate`, `IfcLeapYear`, `IfcValidTime` and the ranges of
19//! `IfcMonthInYearNumber`, `IfcHourInDay`, `IfcMinuteInHour` and
20//! `IfcSecondInMinute`) and staged as those records by the writer that
21//! references it. `ifc-cost` carries an identical copy of these types:
22//! sibling domain crates may not depend on each other, and only `ifc-model`
23//! and `ifc-schema` sit below both.
24
25use ifc_model::{Entity, EntityId, Transaction, Value};
26
27use crate::error::ScheduleAuthoringError;
28
29/// A date, a time or both, as one release or another declares it.
30///
31/// Converts from `&str` for the IFC4/IFC4X3 text form, and from
32/// [`CalendarDate`] and [`LocalTime`] for the IFC2X3 record forms.
33#[derive(Debug, Clone, Copy, PartialEq)]
34#[non_exhaustive]
35pub enum DateTimeValue<'a> {
36    /// IFC4 and IFC4X3 `IfcDateTime`: ISO 8601 text, written as given.
37    Text(&'a str),
38    /// IFC2X3 `IfcCalendarDate`.
39    Date(CalendarDate),
40    /// IFC2X3 `IfcLocalTime`.
41    Time(LocalTime),
42    /// IFC2X3 `IfcDateAndTime`: an `IfcCalendarDate` and an `IfcLocalTime`.
43    DateAndTime(CalendarDate, LocalTime),
44}
45
46impl Default for DateTimeValue<'_> {
47    fn default() -> Self {
48        Self::Text("")
49    }
50}
51
52impl<'a> From<&'a str> for DateTimeValue<'a> {
53    fn from(text: &'a str) -> Self {
54        Self::Text(text)
55    }
56}
57
58impl From<CalendarDate> for DateTimeValue<'_> {
59    fn from(date: CalendarDate) -> Self {
60        Self::Date(date)
61    }
62}
63
64impl From<LocalTime> for DateTimeValue<'_> {
65    fn from(time: LocalTime) -> Self {
66        Self::Time(time)
67    }
68}
69
70/// An IFC2X3 `IfcCalendarDate`: a Gregorian day.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct CalendarDate {
74    /// `YearComponent`.
75    pub year: i64,
76    /// `MonthComponent`, 1 = January through 12 = December.
77    pub month: i64,
78    /// `DayComponent`, a day that exists in that month.
79    pub day: i64,
80}
81
82impl CalendarDate {
83    /// A date; checked when a writer stages it.
84    #[must_use]
85    pub const fn new(year: i64, month: i64, day: i64) -> Self {
86        Self { year, month, day }
87    }
88}
89
90/// An IFC2X3 `IfcLocalTime`: a time of day.
91///
92/// `Zone` and `DaylightSavingOffset` are not carried yet and are written
93/// `$`, which the schema allows.
94#[derive(Debug, Clone, Copy, PartialEq)]
95#[non_exhaustive]
96pub struct LocalTime {
97    /// `HourComponent`, 0 through 23.
98    pub hour: i64,
99    /// `MinuteComponent`, 0 through 59.
100    pub minute: Option<i64>,
101    /// `SecondComponent`, at least 0 and below 60. Requires a minute
102    /// (`IfcValidTime`).
103    pub second: Option<f64>,
104}
105
106impl LocalTime {
107    /// A whole hour; add a minute and second with the setters.
108    #[must_use]
109    pub const fn new(hour: i64) -> Self {
110        Self {
111            hour,
112            minute: None,
113            second: None,
114        }
115    }
116
117    /// Sets `MinuteComponent`.
118    #[must_use]
119    pub const fn minute(mut self, value: i64) -> Self {
120        self.minute = Some(value);
121        self
122    }
123
124    /// Sets `SecondComponent`.
125    #[must_use]
126    pub const fn second(mut self, value: f64) -> Self {
127        self.second = Some(value);
128        self
129    }
130}
131
132fn invalid(
133    entity: &'static str,
134    attribute: &'static str,
135    expected: &'static str,
136) -> ScheduleAuthoringError {
137    ScheduleAuthoringError::InvalidValue {
138        entity,
139        attribute,
140        expected,
141    }
142}
143
144fn leap_year(year: i64) -> bool {
145    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
146}
147
148impl CalendarDate {
149    fn check(self) -> Result<(), ScheduleAuthoringError> {
150        const ENTITY: &str = "IFCCALENDARDATE";
151        if !(1..=12).contains(&self.month) {
152            return Err(invalid(ENTITY, "MonthComponent", "a month in 1..=12"));
153        }
154        let last = match self.month {
155            4 | 6 | 9 | 11 => 30,
156            2 if leap_year(self.year) => 29,
157            2 => 28,
158            _ => 31,
159        };
160        if !(1..=last).contains(&self.day) {
161            return Err(invalid(
162                ENTITY,
163                "DayComponent",
164                "a day that exists in the month (IfcValidCalendarDate)",
165            ));
166        }
167        Ok(())
168    }
169
170    fn stage(self, tx: &mut Transaction) -> EntityId {
171        tx.create(Entity::new(
172            "IFCCALENDARDATE",
173            vec![
174                Value::Integer(self.day),
175                Value::Integer(self.month),
176                Value::Integer(self.year),
177            ],
178        ))
179    }
180}
181
182impl LocalTime {
183    fn check(self) -> Result<(), ScheduleAuthoringError> {
184        const ENTITY: &str = "IFCLOCALTIME";
185        if !(0..24).contains(&self.hour) {
186            return Err(invalid(ENTITY, "HourComponent", "an hour in 0..24"));
187        }
188        if self.minute.is_some_and(|m| !(0..=59).contains(&m)) {
189            return Err(invalid(ENTITY, "MinuteComponent", "a minute in 0..=59"));
190        }
191        if let Some(second) = self.second {
192            if !second.is_finite() || !(0.0..60.0).contains(&second) {
193                return Err(invalid(
194                    ENTITY,
195                    "SecondComponent",
196                    "a finite second in 0.0..60.0",
197                ));
198            }
199            if self.minute.is_none() {
200                return Err(invalid(
201                    ENTITY,
202                    "MinuteComponent",
203                    "a minute when a second is given (IfcValidTime)",
204                ));
205            }
206        }
207        Ok(())
208    }
209
210    fn stage(self, tx: &mut Transaction) -> EntityId {
211        tx.create(Entity::new(
212            "IFCLOCALTIME",
213            vec![
214                Value::Integer(self.hour),
215                self.minute.map_or(Value::Null, Value::Integer),
216                self.second.map_or(Value::Null, Value::Real),
217                Value::Null,
218                Value::Null,
219            ],
220        ))
221    }
222}
223
224impl<'a> DateTimeValue<'a> {
225    /// The text form, if this is one.
226    pub(crate) fn text(self) -> Option<&'a str> {
227        match self {
228            Self::Text(text) => Some(text),
229            _ => None,
230        }
231    }
232
233    /// Check a record form against the schema's rules; text is checked by
234    /// the writer that owns it.
235    pub(crate) fn check(self) -> Result<(), ScheduleAuthoringError> {
236        match self {
237            Self::Text(_) => Ok(()),
238            Self::Date(date) => date.check(),
239            Self::Time(time) => time.check(),
240            Self::DateAndTime(date, time) => {
241                date.check()?;
242                time.check()
243            }
244        }
245    }
246
247    /// The value to lay the owning record out with before anything is
248    /// staged: the text, or `placeholder` standing in for the record.
249    pub(crate) fn provisional(self, placeholder: EntityId) -> Value {
250        match self {
251            Self::Text(text) => Value::Text(text.into()),
252            _ => Value::Ref(placeholder),
253        }
254    }
255
256    /// Stage the records of a record form and return the reference to
257    /// write; `None` for text, which needs no record.
258    pub(crate) fn stage(self, tx: &mut Transaction) -> Option<EntityId> {
259        match self {
260            Self::Text(_) => None,
261            Self::Date(date) => Some(date.stage(tx)),
262            Self::Time(time) => Some(time.stage(tx)),
263            Self::DateAndTime(date, time) => {
264                let date = date.stage(tx);
265                let time = time.stage(tx);
266                Some(tx.create(Entity::new(
267                    "IFCDATEANDTIME",
268                    vec![Value::Ref(date), Value::Ref(time)],
269                )))
270            }
271        }
272    }
273}
274
275/// Placeholders for date references in a record laid out before the dates
276/// are staged. Never staged: each is replaced by [`patch`] first.
277pub(crate) const PLACEHOLDERS: [EntityId; 3] = [
278    EntityId(u64::MAX),
279    EntityId(u64::MAX - 1),
280    EntityId(u64::MAX - 2),
281];
282
283/// Stage each date's records and replace its placeholder in `record`.
284pub(crate) fn patch(
285    tx: &mut Transaction,
286    record: &mut Entity,
287    dates: &[Option<DateTimeValue<'_>>],
288) {
289    for (date, placeholder) in dates.iter().zip(PLACEHOLDERS) {
290        let Some(staged) = date.and_then(|date| date.stage(tx)) else {
291            continue;
292        };
293        for slot in &mut record.attributes {
294            if *slot == Value::Ref(placeholder) {
295                *slot = Value::Ref(staged);
296            }
297        }
298    }
299}