temps-jiff 4.0.0

Jiff integration for temps - time and date parsing library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! # temps-jiff
//!
//! Jiff integration for the temps time expression parser.
//!
//! This crate provides a `JiffProvider` that implements the `TimeParser` trait
//! using the jiff datetime library. It enables parsing natural language time
//! expressions into jiff's `Zoned` type.
//!
//! ## Features
//!
//! - Full implementation of the temps `TimeParser` trait
//! - Support for all time expression types
//! - Proper handling of month/year arithmetic using jiff's `Span`
//! - Timezone support (UTC and fixed offsets)
//! - Precise time calculations with nanosecond precision
//!
//! ## Example
//!
//! ```
//! use temps_jiff::{JiffProvider, parse_to_zoned};
//! use temps_core::{Language, TimeParser};
//!
//! // Parse using the convenience function
//! let datetime = parse_to_zoned("in 5 minutes", Language::English).unwrap();
//! println!("In 5 minutes: {}", datetime);
//!
//! // Or use the provider directly
//! let provider = JiffProvider;
//! let expr = temps_core::parse("tomorrow at 3:30 pm", Language::English).unwrap();
//! let datetime = provider.parse_expression(expr).unwrap();
//! ```
//!
//! ## Month and Year Arithmetic
//!
//! This implementation uses jiff's `Span` type for date arithmetic, which
//! provides correct handling of edge cases:
//!
//! - January 31 + 1 month = February 29 (leap year) or February 28 (non-leap year)
//! - February 29, 2024 + 1 year = February 28, 2025
//!
//! ## Error Handling
//!
//! All parsing operations return `Result<Zoned, TempsError>`. Common errors include:
//!
//! - `ParseError`: Invalid input that cannot be parsed
//! - `DateCalculationError`: Date arithmetic that results in invalid dates
//! - `InvalidDate`/`InvalidTime`: Components that are out of valid ranges
//! - `BackendError`: Errors from the jiff library

use jiff::{Span, Zoned};
use temps_core::{
    DayReference, Direction, Language, Result, TempsError, TimeExpression, TimeParser, TimeUnit,
    Weekday,
    errors::*,
    time_utils::{
        calculate_timezone_offset_seconds, calculate_weekday_offset, convert_12_to_24_hour,
        is_valid_time, is_valid_timezone_offset,
    },
};

/// Jiff-based implementation of the TimeParser trait.
///
/// This provider uses jiff's `Zoned` as its datetime type, providing
/// high-precision time calculations and comprehensive timezone support.
///
/// ## Example
///
/// ```
/// use temps_jiff::JiffProvider;
/// use temps_core::{TimeParser, parse, Language};
///
/// let provider = JiffProvider;
/// let expr = parse("next Monday", Language::English).unwrap();
/// let datetime = provider.parse_expression(expr).unwrap();
/// ```
pub struct JiffProvider;

fn jiff_date_components(year: u16, month: u8, day: u8) -> Result<(i16, i8, i8)> {
    Ok((
        i16::try_from(year).map_err(|_| TempsError::invalid_date(year, month, day))?,
        i8::try_from(month).map_err(|_| TempsError::invalid_date(year, month, day))?,
        i8::try_from(day).map_err(|_| TempsError::invalid_date(year, month, day))?,
    ))
}

fn jiff_time_components(
    hour: u8,
    minute: u8,
    second: u8,
    nanosecond: u32,
) -> Result<(i8, i8, i8, i32)> {
    Ok((
        i8::try_from(hour).map_err(|_| TempsError::invalid_time(hour, minute, second))?,
        i8::try_from(minute).map_err(|_| TempsError::invalid_time(hour, minute, second))?,
        i8::try_from(second).map_err(|_| TempsError::invalid_time(hour, minute, second))?,
        i32::try_from(nanosecond)
            .map_err(|_| TempsError::backend_error("Invalid nanosecond component", "jiff"))?,
    ))
}

impl TimeParser for JiffProvider {
    type DateTime = Zoned;

    fn now(&self) -> Self::DateTime {
        Zoned::now()
    }

    fn parse_expression(&self, expr: TimeExpression) -> Result<Self::DateTime> {
        match expr {
            TimeExpression::Now => Ok(self.now()),
            TimeExpression::Relative(rel) => {
                if rel.amount < 0 {
                    return Err(TempsError::date_calculation(
                        ERR_RELATIVE_AMOUNT_NON_NEGATIVE,
                    ));
                }

                let now = self.now();

                // Create a span based on the time unit
                let span = match rel.unit {
                    TimeUnit::Second => Span::new().seconds(rel.amount),
                    TimeUnit::Minute => Span::new().minutes(rel.amount),
                    TimeUnit::Hour => Span::new().hours(rel.amount),
                    TimeUnit::Day => Span::new().days(rel.amount),
                    TimeUnit::Week => Span::new().weeks(rel.amount),
                    TimeUnit::Month => Span::new().months(rel.amount),
                    TimeUnit::Year => Span::new().years(rel.amount),
                };

                // Apply the span in the correct direction
                match rel.direction {
                    Direction::Past => now.checked_sub(span).map_err(|e| {
                        TempsError::date_calculation_with_source(ERR_DATE_CALC_ERROR, e.to_string())
                    }),
                    Direction::Future => now.checked_add(span).map_err(|e| {
                        TempsError::date_calculation_with_source(ERR_DATE_CALC_ERROR, e.to_string())
                    }),
                }
            }
            TimeExpression::Absolute(abs) => {
                use jiff::civil::{Date, DateTime, Time};
                use jiff::tz::{Offset, TimeZone};

                let (year, month, day) = jiff_date_components(abs.year, abs.month, abs.day)?;
                let date = Date::new(year, month, day)
                    .map_err(|e| TempsError::backend_error(e.to_string(), "jiff"))?;

                if let (Some(hour), Some(minute)) = (abs.hour, abs.minute) {
                    // Validate hour is in valid range (0-23)
                    if hour > 23 {
                        return Err(TempsError::invalid_time(
                            hour,
                            minute,
                            abs.second.unwrap_or(0),
                        ));
                    }
                    // Validate minute is in valid range (0-59)
                    if minute > 59 {
                        return Err(TempsError::invalid_time(
                            hour,
                            minute,
                            abs.second.unwrap_or(0),
                        ));
                    }
                    // Validate second is in valid range (0-59)
                    if let Some(second) = abs.second
                        && second > 59
                    {
                        return Err(TempsError::invalid_time(hour, minute, second));
                    }

                    let second = abs.second.unwrap_or(0);
                    let nanosecond = abs.nanosecond.unwrap_or(0);
                    let (hour, minute, second, nanosecond) =
                        jiff_time_components(hour, minute, second, nanosecond)?;

                    let time = Time::new(hour, minute, second, nanosecond)
                        .map_err(|e| TempsError::backend_error(e.to_string(), "jiff"))?;

                    let datetime = DateTime::from_parts(date, time);

                    match &abs.timezone {
                        Some(temps_core::Timezone::Utc) => datetime
                            .to_zoned(TimeZone::UTC)
                            .map(|z| z.with_time_zone(TimeZone::system()))
                            .map_err(|e| {
                                TempsError::backend_error(
                                    format!("{ERR_TIMEZONE_CONVERSION}: {e}"),
                                    "jiff",
                                )
                            }),
                        Some(temps_core::Timezone::Offset { hours, minutes }) => {
                            if !is_valid_timezone_offset(temps_core::Timezone::Offset {
                                hours: *hours,
                                minutes: *minutes,
                            }) {
                                return Err(TempsError::invalid_timezone_offset(*hours, *minutes));
                            }

                            let total_seconds = calculate_timezone_offset_seconds(*hours, *minutes);
                            let offset = Offset::from_seconds(total_seconds).map_err(|_| {
                                TempsError::invalid_timezone_offset(*hours, *minutes)
                            })?;

                            datetime
                                .to_zoned(TimeZone::fixed(offset))
                                .map(|z| z.with_time_zone(TimeZone::system()))
                                .map_err(|e| {
                                    TempsError::backend_error(
                                        format!("{ERR_TIMEZONE_CONVERSION}: {e}"),
                                        "jiff",
                                    )
                                })
                        }
                        None => {
                            // No timezone specified, treat as system timezone
                            datetime.to_zoned(TimeZone::system()).map_err(|e| {
                                TempsError::backend_error(
                                    format!("{ERR_TIMEZONE_CONVERSION}: {e}"),
                                    "jiff",
                                )
                            })
                        }
                    }
                } else {
                    // Date only, set time to midnight
                    let datetime = date.at(0, 0, 0, 0);
                    datetime.to_zoned(TimeZone::system()).map_err(|e| {
                        TempsError::backend_error(format!("{ERR_TIMEZONE_CONVERSION}: {e}"), "jiff")
                    })
                }
            }
            TimeExpression::Day(day_ref) => {
                let now = self.now();
                match day_ref {
                    DayReference::Today => {
                        let date = now.date();
                        date.at(0, 0, 0, 0)
                            .to_zoned(now.time_zone().clone())
                            .map_err(|e| {
                                TempsError::date_calculation_with_source(
                                    "Failed to create today's date",
                                    e.to_string(),
                                )
                            })
                    }
                    DayReference::Yesterday => {
                        let yesterday = now.checked_sub(Span::new().days(1)).map_err(|e| {
                            TempsError::date_calculation_with_source(
                                "Failed to calculate yesterday",
                                e.to_string(),
                            )
                        })?;
                        let date = yesterday.date();
                        date.at(0, 0, 0, 0)
                            .to_zoned(now.time_zone().clone())
                            .map_err(|e| {
                                TempsError::date_calculation_with_source(
                                    "Failed to create yesterday's date",
                                    e.to_string(),
                                )
                            })
                    }
                    DayReference::Tomorrow => {
                        let tomorrow = now.checked_add(Span::new().days(1)).map_err(|e| {
                            TempsError::date_calculation_with_source(
                                "Failed to calculate tomorrow",
                                e.to_string(),
                            )
                        })?;
                        let date = tomorrow.date();
                        date.at(0, 0, 0, 0)
                            .to_zoned(now.time_zone().clone())
                            .map_err(|e| {
                                TempsError::date_calculation_with_source(
                                    "Failed to create tomorrow's date",
                                    e.to_string(),
                                )
                            })
                    }
                    DayReference::Weekday { day, modifier } => {
                        let target_weekday = match day {
                            Weekday::Monday => jiff::civil::Weekday::Monday,
                            Weekday::Tuesday => jiff::civil::Weekday::Tuesday,
                            Weekday::Wednesday => jiff::civil::Weekday::Wednesday,
                            Weekday::Thursday => jiff::civil::Weekday::Thursday,
                            Weekday::Friday => jiff::civil::Weekday::Friday,
                            Weekday::Saturday => jiff::civil::Weekday::Saturday,
                            Weekday::Sunday => jiff::civil::Weekday::Sunday,
                        };

                        let current_weekday = now.weekday();
                        let current_offset = current_weekday.to_monday_zero_offset() as i64;
                        let target_offset = target_weekday.to_monday_zero_offset() as i64;

                        let days_to_add =
                            calculate_weekday_offset(current_offset, target_offset, modifier);
                        let target_date = now.checked_add(Span::new().days(days_to_add));

                        let target = target_date.map_err(|e| {
                            TempsError::date_calculation_with_source(
                                "Failed to calculate weekday",
                                e.to_string(),
                            )
                        })?;
                        let date = target.date();
                        date.at(0, 0, 0, 0)
                            .to_zoned(now.time_zone().clone())
                            .map_err(|e| {
                                TempsError::date_calculation_with_source(
                                    "Failed to create weekday date",
                                    e.to_string(),
                                )
                            })
                    }
                }
            }
            TimeExpression::Time(time) => {
                let now = self.now();
                let date = now.date();

                if !is_valid_time(time.hour, time.minute, time.second, time.meridiem) {
                    return Err(TempsError::invalid_time(
                        time.hour,
                        time.minute,
                        time.second,
                    ));
                }

                let hour = convert_12_to_24_hour(time.hour, time.meridiem.as_ref());

                let (hour, minute, second, nanosecond) =
                    jiff_time_components(hour, time.minute, time.second, 0)?;

                date.at(hour, minute, second, nanosecond)
                    .to_zoned(now.time_zone().clone())
                    .map_err(|e| {
                        TempsError::backend_error(format!("Failed to create time: {e}"), "jiff")
                    })
            }
            TimeExpression::DayTime(day_time) => {
                // First get the day
                let day_result = self.parse_expression(TimeExpression::Day(day_time.day))?;
                let date = day_result.date();

                if !is_valid_time(
                    day_time.time.hour,
                    day_time.time.minute,
                    day_time.time.second,
                    day_time.time.meridiem,
                ) {
                    return Err(TempsError::invalid_time(
                        day_time.time.hour,
                        day_time.time.minute,
                        day_time.time.second,
                    ));
                }

                let hour =
                    convert_12_to_24_hour(day_time.time.hour, day_time.time.meridiem.as_ref());

                let (hour, minute, second, nanosecond) =
                    jiff_time_components(hour, day_time.time.minute, day_time.time.second, 0)?;

                date.at(hour, minute, second, nanosecond)
                    .to_zoned(day_result.time_zone().clone())
                    .map_err(|e| {
                        TempsError::backend_error(format!("Failed to create day time: {e}"), "jiff")
                    })
            }
            TimeExpression::Date(date) => {
                use jiff::civil::Date;

                let (year, month, day) = jiff_date_components(date.year, date.month, date.day)?;
                let jiff_date = Date::new(year, month, day)
                    .map_err(|_| TempsError::invalid_date(date.year, date.month, date.day))?;

                jiff_date
                    .at(0, 0, 0, 0)
                    .to_zoned(jiff::tz::TimeZone::system())
                    .map_err(|e| {
                        TempsError::backend_error(format!("Failed to create date: {e}"), "jiff")
                    })
            }
        }
    }
}

/// Parse a natural language time expression into a jiff `Zoned` datetime.
///
/// This is a convenience function that combines parsing and time calculation
/// in a single call.
///
/// # Arguments
///
/// * `input` - The natural language time expression to parse
/// * `language` - The language to use for parsing
///
/// # Returns
///
/// Returns `Ok(Zoned)` if parsing succeeds, or `Err(TempsError)`
/// if the input cannot be parsed or the date calculation fails.
///
/// # Examples
///
/// ```
/// use temps_jiff::parse_to_zoned;
/// use temps_core::Language;
///
/// // Parse English expressions
/// let dt = parse_to_zoned("in 30 minutes", Language::English).unwrap();
/// let dt = parse_to_zoned("tomorrow at 12:00", Language::English).unwrap();
/// let dt = parse_to_zoned("last Monday", Language::English).unwrap();
///
/// // Parse German expressions  
/// let dt = parse_to_zoned("in 30 Minuten", Language::German).unwrap();
/// let dt = parse_to_zoned("morgen um 15:30", Language::German).unwrap();
/// ```
///
/// # Errors
///
/// This function will return an error if:
/// - The input cannot be parsed as a valid time expression
/// - Date calculation results in an invalid date
/// - Components are out of valid ranges (e.g., month 13)
/// - The jiff library returns an error during calculations
pub fn parse_to_zoned(input: &str, language: Language) -> Result<Zoned> {
    let expr = temps_core::parse(input, language)?;
    JiffProvider.parse_expression(expr)
}