quack_rs/interval.rs
1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! `DuckDB` `INTERVAL` type conversion utilities.
7//!
8//! A `DuckDB` `INTERVAL` is a 16-byte struct with three fields:
9//! ```text
10//! { months: i32, days: i32, micros: i64 }
11//! ```
12//!
13//! Converting to a uniform unit (microseconds) requires careful arithmetic to
14//! avoid integer overflow. This module provides checked and saturating conversions.
15//!
16//! # Pitfall P8: Undocumented INTERVAL layout
17//!
18//! The `duckdb_string_t` and `INTERVAL` struct layouts are not documented in the
19//! Rust bindings (`libduckdb-sys`). They must be inferred from `DuckDB`'s C headers.
20//! This module encodes that knowledge so extension authors never need to look it up.
21//!
22//! # Example
23//!
24//! ```rust
25//! use quack_rs::interval::{interval_to_micros, DuckInterval};
26//!
27//! let iv = DuckInterval { months: 1, days: 0, micros: 0 };
28//! // 1 month ≈ 30 days = 2_592_000_000_000 microseconds
29//! assert_eq!(interval_to_micros(iv), Some(2_592_000_000_000_i64));
30//! ```
31
32/// Microseconds per day, used for interval conversion.
33pub const MICROS_PER_DAY: i64 = 86_400 * 1_000_000;
34
35/// Microseconds per month, approximated as 30 days — `DuckDB`'s
36/// `Interval::MICROS_PER_MONTH`, used for comparing intervals (see
37/// [`interval_to_micros`] for where `DuckDB` does and does not use it).
38pub const MICROS_PER_MONTH: i64 = 30 * MICROS_PER_DAY;
39
40/// A `DuckDB` `INTERVAL` value, matching the C struct layout exactly.
41///
42/// # Memory layout
43///
44/// ```text
45/// offset 0: months (i32) — number of calendar months
46/// offset 4: days (i32) — number of calendar days
47/// offset 8: micros (i64) — microseconds component
48/// total: 16 bytes
49/// ```
50///
51/// # Equality is field-by-field, not SQL equality
52///
53/// The derived `PartialEq`, `Eq` and `Hash` compare the three fields, so
54/// `{ months: 1, .. }` and `{ days: 30, .. }` are different values here while
55/// `DuckDB` says `interval '1 month' = interval '30 days'`. Comparing
56/// [`to_micros`][Self::to_micros] matches SQL when the three fields share a
57/// sign; see [`interval_to_micros`] for the mixed-sign case where it does not.
58///
59/// # Safety
60///
61/// This struct must remain `#[repr(C)]` with the exact field order above,
62/// matching `DuckDB`'s `duckdb_interval` C struct.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64#[repr(C)]
65pub struct DuckInterval {
66 /// Calendar months component.
67 pub months: i32,
68 /// Calendar days component.
69 pub days: i32,
70 /// Microseconds component. `DuckDB` does not fold it into days:
71 /// `INTERVAL '48 hours'` has 0 days and 172,800,000,000 microseconds.
72 pub micros: i64,
73}
74
75impl DuckInterval {
76 /// Returns a zero-valued interval (0 months, 0 days, 0 microseconds).
77 #[inline]
78 #[must_use]
79 pub const fn zero() -> Self {
80 Self {
81 months: 0,
82 days: 0,
83 micros: 0,
84 }
85 }
86
87 /// Converts this interval to total microseconds with overflow checking.
88 ///
89 /// Returns `None` if the result would overflow `i64`.
90 ///
91 /// Month conversion uses 30 days/month; see [`interval_to_micros`] for
92 /// where that matches `DuckDB` and where it does not.
93 ///
94 /// # Example
95 ///
96 /// ```rust
97 /// use quack_rs::interval::DuckInterval;
98 ///
99 /// let iv = DuckInterval { months: 0, days: 1, micros: 500_000 };
100 /// assert_eq!(iv.to_micros(), Some(86_400_500_000_i64));
101 /// ```
102 #[inline]
103 #[must_use]
104 pub fn to_micros(self) -> Option<i64> {
105 interval_to_micros(self)
106 }
107
108 /// Converts this interval to total microseconds, saturating on overflow.
109 ///
110 /// # Example
111 ///
112 /// ```rust
113 /// use quack_rs::interval::DuckInterval;
114 ///
115 /// let iv = DuckInterval { months: i32::MAX, days: i32::MAX, micros: i64::MAX };
116 /// assert_eq!(iv.to_micros_saturating(), i64::MAX);
117 /// ```
118 #[inline]
119 #[must_use]
120 pub fn to_micros_saturating(self) -> i64 {
121 interval_to_micros_saturating(self)
122 }
123}
124
125impl Default for DuckInterval {
126 #[inline]
127 fn default() -> Self {
128 Self::zero()
129 }
130}
131
132/// Converts a [`DuckInterval`] to total microseconds with overflow checking.
133///
134/// Uses the approximation: **1 month = 30 days**. `DuckDB` uses the same
135/// approximation in exactly two places (checked on `DuckDB` 1.4.4 and 1.5.5):
136///
137/// - **Comparing intervals** — `interval '1 month' = interval '30 days'` is
138/// `true` (`Interval::DAYS_PER_MONTH = 30` in `interval.hpp`). `DuckDB`
139/// normalises the fields (`interval_t::Normalize`: micros carry into days,
140/// days into months, with truncating division) and compares them in order, so
141/// this agrees with comparing total microseconds only when the fields do
142/// not mix signs: `interval '1 month' - interval '1 day'` equals
143/// `interval '29 days'` in microseconds but compares **greater** in SQL.
144/// - **`epoch_us(interval)`** — returns exactly what this function returns
145/// whenever it returns a value; `epoch_us(interval '1 year')` is 360 days.
146/// `DuckDB` adds the fields one at a time in `i64` (`Interval::GetMicro`)
147/// and fails with "Could not convert Day to Microseconds" when one of them
148/// overflows on its own, as `106751992 days -86400000000 microseconds`
149/// does; this function computes the exact total and returns it whenever
150/// the total fits.
151///
152/// It is **not** what `DuckDB` does elsewhere: `interval + interval` keeps
153/// months, days and micros separate (`1 month 30 days`), adding an interval to
154/// a date uses calendar months (`2024-01-31 + 1 month` is `2024-02-29`), and
155/// `epoch(interval '1 year')` counts 365.25 days. Use this conversion for
156/// ordering or bucketing intervals, not for date arithmetic.
157///
158/// # Returns
159///
160/// `None` if the total does not fit in an `i64`. Intermediate results never
161/// overflow: the sum is computed exactly, so `{months: 2770036, days:
162/// 31299404, micros: -2032753245989188716}`, whose months and days alone
163/// exceed `i64::MAX`, converts to `7851448571610811284`.
164///
165/// # Example
166///
167/// ```rust
168/// use quack_rs::interval::{interval_to_micros, DuckInterval};
169///
170/// // 2 hours 30 minutes = 9_000_000_000 microseconds
171/// let iv = DuckInterval { months: 0, days: 0, micros: 9_000_000_000 };
172/// assert_eq!(interval_to_micros(iv), Some(9_000_000_000_i64));
173///
174/// // 1 day
175/// let iv = DuckInterval { months: 0, days: 1, micros: 0 };
176/// assert_eq!(interval_to_micros(iv), Some(86_400_000_000_i64));
177///
178/// // Overflow returns None
179/// let iv = DuckInterval { months: i32::MAX, days: i32::MAX, micros: i64::MAX };
180/// assert_eq!(interval_to_micros(iv), None);
181/// ```
182#[inline]
183pub fn interval_to_micros(iv: DuckInterval) -> Option<i64> {
184 i64::try_from(total_micros_i128(iv)).ok()
185}
186
187/// The exact total in microseconds (1 month = 30 days). It cannot overflow
188/// `i128`: each product is below 2^32 · 2^42 in magnitude, and the sum of
189/// three terms below 2^75 stays far inside 2^127.
190fn total_micros_i128(iv: DuckInterval) -> i128 {
191 i128::from(iv.months) * i128::from(MICROS_PER_MONTH)
192 + i128::from(iv.days) * i128::from(MICROS_PER_DAY)
193 + i128::from(iv.micros)
194}
195
196/// Converts a [`DuckInterval`] to total microseconds, saturating on overflow.
197///
198/// Uses the approximation: **1 month = 30 days**.
199///
200/// # Example
201///
202/// ```rust
203/// use quack_rs::interval::{interval_to_micros_saturating, DuckInterval};
204///
205/// let iv = DuckInterval { months: 0, days: 0, micros: 1_000_000 };
206/// assert_eq!(interval_to_micros_saturating(iv), 1_000_000_i64);
207/// ```
208#[inline]
209pub fn interval_to_micros_saturating(iv: DuckInterval) -> i64 {
210 let total = total_micros_i128(iv);
211 i64::try_from(total).unwrap_or(if total >= 0 { i64::MAX } else { i64::MIN })
212}
213
214/// Reads a [`DuckInterval`] from a raw `DuckDB` vector data pointer at a given row index.
215///
216/// # Safety
217///
218/// - `data` must be a valid pointer to a `DuckDB` vector's data buffer containing
219/// `INTERVAL` values (16 bytes each).
220/// - `idx` must be within bounds of the vector.
221///
222/// # Pitfall P8
223///
224/// The `INTERVAL` struct is 16 bytes: `{ months: i32, days: i32, micros: i64 }`.
225/// This layout matches `duckdb_interval` in `DuckDB`'s C headers.
226///
227/// # Example
228///
229/// ```rust
230/// use quack_rs::interval::{read_interval_at, DuckInterval};
231///
232/// let ivs = [DuckInterval { months: 2, days: 15, micros: 1_000 }];
233/// let data = ivs.as_ptr() as *const u8;
234/// let read = unsafe { read_interval_at(data, 0) };
235/// assert_eq!(read.months, 2);
236/// assert_eq!(read.days, 15);
237/// assert_eq!(read.micros, 1_000);
238/// ```
239#[inline]
240pub const unsafe fn read_interval_at(data: *const u8, idx: usize) -> DuckInterval {
241 // SAFETY: Each INTERVAL is exactly 16 bytes (repr(C) struct with i32, i32, i64).
242 // The caller guarantees `data` points to valid INTERVAL data and `idx` is in bounds.
243 let ptr = unsafe { data.add(idx * 16) };
244 // SAFETY: `ptr` is the start of the 16-byte INTERVAL at row `idx` inside the buffer
245 // `data` points to (both `# Safety` clauses), so `ptr + 0` through `+ 4` are
246 // initialised bytes of that element (`months: i32`); `read_unaligned` needs no
247 // alignment, only readable memory.
248 let months = unsafe { core::ptr::read_unaligned(ptr.cast::<i32>()) };
249 // SAFETY: `ptr` is the start of the 16-byte INTERVAL at row `idx` inside the buffer
250 // `data` points to (both `# Safety` clauses), so `ptr + 4` through `+ 8` are
251 // initialised bytes of that element (`days: i32`); `read_unaligned` needs no alignment,
252 // only readable memory.
253 let days = unsafe { core::ptr::read_unaligned(ptr.add(4).cast::<i32>()) };
254 // SAFETY: `ptr` is the start of the 16-byte INTERVAL at row `idx` inside the buffer
255 // `data` points to (both `# Safety` clauses), so `ptr + 8` through `+ 16` are
256 // initialised bytes of that element (`micros: i64`); `read_unaligned` needs no
257 // alignment, only readable memory.
258 let micros = unsafe { core::ptr::read_unaligned(ptr.add(8).cast::<i64>()) };
259 DuckInterval {
260 months,
261 days,
262 micros,
263 }
264}
265
266/// Asserts the size and alignment of [`DuckInterval`] match `DuckDB`'s C struct.
267const _: () = {
268 assert!(
269 core::mem::size_of::<DuckInterval>() == 16,
270 "DuckInterval must be exactly 16 bytes"
271 );
272 assert!(
273 core::mem::align_of::<DuckInterval>() >= 4,
274 "DuckInterval must have at least 4-byte alignment"
275 );
276};
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 #[test]
283 fn size_of_duck_interval() {
284 assert_eq!(core::mem::size_of::<DuckInterval>(), 16);
285 }
286
287 #[test]
288 fn zero_interval() {
289 let iv = DuckInterval::zero();
290 assert_eq!(interval_to_micros(iv), Some(0));
291 }
292
293 #[test]
294 fn default_interval() {
295 let iv = DuckInterval::default();
296 assert_eq!(iv, DuckInterval::zero());
297 }
298
299 #[test]
300 fn one_day() {
301 let iv = DuckInterval {
302 months: 0,
303 days: 1,
304 micros: 0,
305 };
306 assert_eq!(interval_to_micros(iv), Some(MICROS_PER_DAY));
307 }
308
309 #[test]
310 fn one_month() {
311 let iv = DuckInterval {
312 months: 1,
313 days: 0,
314 micros: 0,
315 };
316 assert_eq!(interval_to_micros(iv), Some(MICROS_PER_MONTH));
317 }
318
319 #[test]
320 fn combined_interval() {
321 let iv = DuckInterval {
322 months: 0,
323 days: 1,
324 micros: 500_000,
325 };
326 let expected = MICROS_PER_DAY + 500_000;
327 assert_eq!(interval_to_micros(iv), Some(expected));
328 }
329
330 #[test]
331 fn negative_interval() {
332 let iv = DuckInterval {
333 months: -1,
334 days: 0,
335 micros: 0,
336 };
337 assert_eq!(interval_to_micros(iv), Some(-MICROS_PER_MONTH));
338 }
339
340 #[test]
341 fn overflow_returns_none() {
342 let iv = DuckInterval {
343 months: i32::MAX,
344 days: i32::MAX,
345 micros: i64::MAX,
346 };
347 assert_eq!(interval_to_micros(iv), None);
348 }
349
350 #[test]
351 fn saturating_on_overflow() {
352 let iv = DuckInterval {
353 months: i32::MAX,
354 days: i32::MAX,
355 micros: i64::MAX,
356 };
357 assert_eq!(interval_to_micros_saturating(iv), i64::MAX);
358 }
359
360 #[test]
361 fn saturating_no_overflow() {
362 let iv = DuckInterval {
363 months: 0,
364 days: 0,
365 micros: 42,
366 };
367 assert_eq!(interval_to_micros_saturating(iv), 42);
368 }
369
370 /// The total fits even though an intermediate sum or product does not:
371 /// adding the fields left to right in `i64` reported overflow (and the
372 /// saturating form returned `i64::MAX`) for both. `DuckDB`'s
373 /// `epoch_us` returns the first value and errors on the second.
374 #[test]
375 fn a_total_that_fits_converts_even_when_an_intermediate_does_not() {
376 let months_and_days_overflow = DuckInterval {
377 months: 2_770_036,
378 days: 31_299_404,
379 micros: -2_032_753_245_989_188_716,
380 };
381 assert_eq!(
382 interval_to_micros(months_and_days_overflow),
383 Some(7_851_448_571_610_811_284)
384 );
385 assert_eq!(
386 interval_to_micros_saturating(months_and_days_overflow),
387 7_851_448_571_610_811_284
388 );
389 let days_alone_overflow = DuckInterval {
390 months: 0,
391 days: 106_751_992,
392 micros: -86_400_000_000,
393 };
394 assert_eq!(
395 days_alone_overflow.to_micros(),
396 Some(9_223_372_022_400_000_000)
397 );
398 assert_eq!(
399 days_alone_overflow.to_micros_saturating(),
400 9_223_372_022_400_000_000
401 );
402 }
403
404 #[test]
405 fn to_micros_method() {
406 let iv = DuckInterval {
407 months: 0,
408 days: 0,
409 micros: 12345,
410 };
411 assert_eq!(iv.to_micros(), Some(12345));
412 }
413
414 #[test]
415 fn to_micros_saturating_method() {
416 let iv = DuckInterval {
417 months: 0,
418 days: 0,
419 micros: 12345,
420 };
421 assert_eq!(iv.to_micros_saturating(), 12345);
422 }
423
424 #[test]
425 fn read_interval_at_basic() {
426 let data = [
427 DuckInterval {
428 months: 2,
429 days: 15,
430 micros: 999_000,
431 },
432 DuckInterval {
433 months: -1,
434 days: 3,
435 micros: 0,
436 },
437 ];
438 // SAFETY: data is a valid array of DuckInterval, idx 0 and 1 are in bounds.
439 let iv0 = unsafe { read_interval_at(data.as_ptr().cast::<u8>(), 0) };
440 assert_eq!(iv0.months, 2);
441 assert_eq!(iv0.days, 15);
442 assert_eq!(iv0.micros, 999_000);
443
444 let iv1 = unsafe { read_interval_at(data.as_ptr().cast::<u8>(), 1) };
445 assert_eq!(iv1.months, -1);
446 assert_eq!(iv1.days, 3);
447 assert_eq!(iv1.micros, 0);
448 }
449
450 #[test]
451 fn exactly_max_i64_micros_no_overflow() {
452 // If all overflow is in micros only (months=0, days=0), no overflow
453 let iv = DuckInterval {
454 months: 0,
455 days: 0,
456 micros: i64::MAX,
457 };
458 assert_eq!(interval_to_micros(iv), Some(i64::MAX));
459 }
460
461 #[test]
462 fn months_calculation() {
463 // 12 months = 12 * 30 days * 86400 * 1_000_000 us
464 let iv = DuckInterval {
465 months: 12,
466 days: 0,
467 micros: 0,
468 };
469 let expected = 12_i64 * MICROS_PER_MONTH;
470 assert_eq!(interval_to_micros(iv), Some(expected));
471 }
472
473 /// `DuckDB`'s `Interval::MICROS_PER_MONTH` is 30 days: `epoch_us(interval
474 /// '1 month')` is `2_592_000_000_000`. Spelled out as a literal so the
475 /// constant is checked, not reused.
476 #[test]
477 fn one_month_is_thirty_days_of_micros() {
478 assert_eq!(MICROS_PER_MONTH, 2_592_000_000_000);
479 let iv = DuckInterval {
480 months: 1,
481 days: 0,
482 micros: 0,
483 };
484 assert_eq!(interval_to_micros(iv), Some(2_592_000_000_000));
485 assert_eq!(
486 interval_to_micros(iv),
487 interval_to_micros(DuckInterval {
488 months: 0,
489 days: 30,
490 micros: 0,
491 })
492 );
493 }
494
495 // Mixed-sign overflow saturation tests (CRIT-5 regression tests)
496
497 /// When only the final micros addition overflows, the true total has the
498 /// sign of the micros, even though the days component is far smaller in
499 /// magnitude: one day plus `i64::MAX` micros saturates up, minus one day
500 /// plus `i64::MIN` micros saturates down.
501 #[test]
502 fn saturation_direction_follows_micros_when_micros_overflow() {
503 let up = DuckInterval {
504 months: 0,
505 days: 1,
506 micros: i64::MAX,
507 };
508 assert_eq!(interval_to_micros(up), None);
509 assert_eq!(interval_to_micros_saturating(up), i64::MAX);
510
511 let down = DuckInterval {
512 months: 0,
513 days: -1,
514 micros: i64::MIN,
515 };
516 assert_eq!(interval_to_micros(down), None);
517 assert_eq!(interval_to_micros_saturating(down), i64::MIN);
518 }
519
520 #[test]
521 fn saturating_positive_overflow_with_negative_days() {
522 // months = i32::MAX overflows to massive positive; days = -1 is tiny negative.
523 // True result is still massively positive → should saturate to i64::MAX.
524 let iv = DuckInterval {
525 months: i32::MAX,
526 days: -1,
527 micros: 0,
528 };
529 assert_eq!(interval_to_micros(iv), None); // confirm it overflows
530 assert_eq!(interval_to_micros_saturating(iv), i64::MAX);
531 }
532
533 #[test]
534 fn saturating_negative_overflow_with_positive_days() {
535 // months = i32::MIN overflows to massive negative; days = 1 is tiny positive.
536 // True result is still massively negative → should saturate to i64::MIN.
537 let iv = DuckInterval {
538 months: i32::MIN,
539 days: 1,
540 micros: 0,
541 };
542 assert_eq!(interval_to_micros(iv), None);
543 assert_eq!(interval_to_micros_saturating(iv), i64::MIN);
544 }
545
546 #[test]
547 fn saturating_positive_overflow_negative_micros() {
548 // Months alone overflow positive; negative micros doesn't change sign.
549 let iv = DuckInterval {
550 months: i32::MAX,
551 days: 0,
552 micros: -1_000_000,
553 };
554 assert_eq!(interval_to_micros(iv), None);
555 assert_eq!(interval_to_micros_saturating(iv), i64::MAX);
556 }
557
558 /// The days term alone decides the direction: it overflows, outweighs
559 /// months and micros of the other sign, and is itself far past `i64`.
560 /// Only the randomized `saturating_direction_matches_i128` reached this
561 /// case before, so CI's mutation job caught `days * MICROS_PER_DAY` ->
562 /// `days + MICROS_PER_DAY` on some runs and not others.
563 #[test]
564 fn saturation_direction_follows_days_when_days_dominate() {
565 let down = DuckInterval {
566 months: 1_000_000,
567 days: i32::MIN,
568 micros: i64::MAX,
569 };
570 assert_eq!(interval_to_micros(down), None);
571 assert_eq!(interval_to_micros_saturating(down), i64::MIN);
572
573 let up = DuckInterval {
574 months: -1_000_000,
575 days: i32::MAX,
576 micros: i64::MIN,
577 };
578 assert_eq!(interval_to_micros(up), None);
579 assert_eq!(interval_to_micros_saturating(up), i64::MAX);
580 }
581
582 #[test]
583 fn saturating_negative_overflow_all_negative() {
584 let iv = DuckInterval {
585 months: i32::MIN,
586 days: i32::MIN,
587 micros: i64::MIN,
588 };
589 assert_eq!(interval_to_micros(iv), None);
590 assert_eq!(interval_to_micros_saturating(iv), i64::MIN);
591 }
592
593 mod proptest_interval {
594 use super::*;
595 use proptest::prelude::*;
596
597 proptest! {
598 #[test]
599 fn micros_only_never_overflows_within_i64(micros: i64) {
600 let iv = DuckInterval { months: 0, days: 0, micros };
601 // micros-only interval always succeeds (no multiplication needed)
602 assert_eq!(interval_to_micros(iv), Some(micros));
603 }
604
605 #[test]
606 fn saturating_never_panics(months: i32, days: i32, micros: i64) {
607 let iv = DuckInterval { months, days, micros };
608 // Must not panic for any input
609 let _ = interval_to_micros_saturating(iv);
610 }
611
612 #[test]
613 fn saturating_direction_matches_i128(months: i32, days: i32, micros: i64) {
614 let iv = DuckInterval { months, days, micros };
615 let sat = interval_to_micros_saturating(iv);
616 if interval_to_micros(iv).is_none() {
617 // Verify saturation direction using i128 ground truth
618 let total = i128::from(months) * i128::from(MICROS_PER_MONTH)
619 + i128::from(days) * i128::from(MICROS_PER_DAY)
620 + i128::from(micros);
621 if total >= 0 {
622 prop_assert_eq!(sat, i64::MAX);
623 } else {
624 prop_assert_eq!(sat, i64::MIN);
625 }
626 }
627 }
628
629 /// Both conversions against the exact total over the whole input
630 /// space: the checked one is `Some` exactly when the total fits,
631 /// and the saturating one is the total clamped to `i64`.
632 #[test]
633 fn both_conversions_match_the_exact_total(months: i32, days: i32, micros: i64) {
634 let iv = DuckInterval { months, days, micros };
635 let total = i128::from(months) * 2_592_000_000_000
636 + i128::from(days) * 86_400_000_000
637 + i128::from(micros);
638 prop_assert_eq!(interval_to_micros(iv), i64::try_from(total).ok());
639 let clamped = total.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
640 prop_assert_eq!(i128::from(interval_to_micros_saturating(iv)), clamped);
641 }
642
643 #[test]
644 fn checked_and_saturating_agree_when_no_overflow(months in -100_i32..=100_i32, days in -100_i32..=100_i32, micros in -1_000_000_i64..=1_000_000_i64) {
645 let iv = DuckInterval { months, days, micros };
646 if let Some(checked) = interval_to_micros(iv) {
647 assert_eq!(interval_to_micros_saturating(iv), checked);
648 }
649 }
650 }
651 }
652}