quack-rs 0.12.0

Production-grade Rust SDK for building DuckDB loadable extensions
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. <https://github.com/tomtom215/>
// My way of giving something small back to the open source community
// and encouraging more Rust development!

//! `DuckDB` `INTERVAL` type conversion utilities.
//!
//! A `DuckDB` `INTERVAL` is a 16-byte struct with three fields:
//! ```text
//! { months: i32, days: i32, micros: i64 }
//! ```
//!
//! Converting to a uniform unit (microseconds) requires careful arithmetic to
//! avoid integer overflow. This module provides checked and saturating conversions.
//!
//! # Pitfall P8: Undocumented INTERVAL layout
//!
//! The `duckdb_string_t` and `INTERVAL` struct layouts are not documented in the
//! Rust bindings (`libduckdb-sys`). They must be inferred from `DuckDB`'s C headers.
//! This module encodes that knowledge so extension authors never need to look it up.
//!
//! # Example
//!
//! ```rust
//! use quack_rs::interval::{interval_to_micros, DuckInterval};
//!
//! let iv = DuckInterval { months: 1, days: 0, micros: 0 };
//! // 1 month ≈ 30 days = 2_592_000_000_000 microseconds
//! assert_eq!(interval_to_micros(iv), Some(2_592_000_000_000_i64));
//! ```

/// Microseconds per day, used for interval conversion.
pub const MICROS_PER_DAY: i64 = 86_400 * 1_000_000;

/// Microseconds per month (approximated as 30 days, matching `DuckDB`'s behaviour).
pub const MICROS_PER_MONTH: i64 = 30 * MICROS_PER_DAY;

/// A `DuckDB` `INTERVAL` value, matching the C struct layout exactly.
///
/// # Memory layout
///
/// ```text
/// offset 0:  months (i32)  — number of calendar months
/// offset 4:  days   (i32)  — number of calendar days
/// offset 8:  micros (i64)  — microseconds component
/// total:     16 bytes
/// ```
///
/// # Safety
///
/// This struct must remain `#[repr(C)]` with the exact field order above,
/// matching `DuckDB`'s `duckdb_interval` C struct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct DuckInterval {
    /// Calendar months component.
    pub months: i32,
    /// Calendar days component.
    pub days: i32,
    /// Sub-day microseconds component.
    pub micros: i64,
}

impl DuckInterval {
    /// Returns a zero-valued interval (0 months, 0 days, 0 microseconds).
    #[inline]
    #[must_use]
    pub const fn zero() -> Self {
        Self {
            months: 0,
            days: 0,
            micros: 0,
        }
    }

    /// Converts this interval to total microseconds with overflow checking.
    ///
    /// Returns `None` if the result would overflow `i64`.
    ///
    /// Month conversion uses 30 days/month, matching `DuckDB`'s approximation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use quack_rs::interval::DuckInterval;
    ///
    /// let iv = DuckInterval { months: 0, days: 1, micros: 500_000 };
    /// assert_eq!(iv.to_micros(), Some(86_400_500_000_i64));
    /// ```
    #[inline]
    #[must_use]
    pub fn to_micros(self) -> Option<i64> {
        interval_to_micros(self)
    }

    /// Converts this interval to total microseconds, saturating on overflow.
    ///
    /// # Example
    ///
    /// ```rust
    /// use quack_rs::interval::DuckInterval;
    ///
    /// let iv = DuckInterval { months: i32::MAX, days: i32::MAX, micros: i64::MAX };
    /// assert_eq!(iv.to_micros_saturating(), i64::MAX);
    /// ```
    #[inline]
    #[must_use]
    pub fn to_micros_saturating(self) -> i64 {
        interval_to_micros_saturating(self)
    }
}

impl Default for DuckInterval {
    #[inline]
    fn default() -> Self {
        Self::zero()
    }
}

/// Converts a [`DuckInterval`] to total microseconds with overflow checking.
///
/// Uses the approximation: **1 month = 30 days**, which is what `DuckDB` uses
/// internally when comparing or arithmetically combining intervals.
///
/// # Returns
///
/// `None` if any intermediate multiplication or addition overflows `i64`.
///
/// # Example
///
/// ```rust
/// use quack_rs::interval::{interval_to_micros, DuckInterval};
///
/// // 2 hours 30 minutes = 9_000_000_000 microseconds
/// let iv = DuckInterval { months: 0, days: 0, micros: 9_000_000_000 };
/// assert_eq!(interval_to_micros(iv), Some(9_000_000_000_i64));
///
/// // 1 day
/// let iv = DuckInterval { months: 0, days: 1, micros: 0 };
/// assert_eq!(interval_to_micros(iv), Some(86_400_000_000_i64));
///
/// // Overflow returns None
/// let iv = DuckInterval { months: i32::MAX, days: i32::MAX, micros: i64::MAX };
/// assert_eq!(interval_to_micros(iv), None);
/// ```
#[inline]
pub fn interval_to_micros(iv: DuckInterval) -> Option<i64> {
    let months_us = i64::from(iv.months).checked_mul(MICROS_PER_MONTH)?;
    let days_us = i64::from(iv.days).checked_mul(MICROS_PER_DAY)?;
    months_us.checked_add(days_us)?.checked_add(iv.micros)
}

/// Converts a [`DuckInterval`] to total microseconds, saturating on overflow.
///
/// Uses the approximation: **1 month = 30 days**.
///
/// # Example
///
/// ```rust
/// use quack_rs::interval::{interval_to_micros_saturating, DuckInterval};
///
/// let iv = DuckInterval { months: 0, days: 0, micros: 1_000_000 };
/// assert_eq!(interval_to_micros_saturating(iv), 1_000_000_i64);
/// ```
#[inline]
pub fn interval_to_micros_saturating(iv: DuckInterval) -> i64 {
    interval_to_micros(iv).unwrap_or_else(|| {
        // Determine sign of the true (overflowed) result using i128 arithmetic.
        // This correctly handles mixed-sign cases where some components are
        // positive and others are negative.
        let months_us = i128::from(iv.months) * i128::from(MICROS_PER_MONTH);
        let days_us = i128::from(iv.days) * i128::from(MICROS_PER_DAY);
        let total = months_us + days_us + i128::from(iv.micros);
        if total >= 0 {
            i64::MAX
        } else {
            i64::MIN
        }
    })
}

/// Reads a [`DuckInterval`] from a raw `DuckDB` vector data pointer at a given row index.
///
/// # Safety
///
/// - `data` must be a valid pointer to a `DuckDB` vector's data buffer containing
///   `INTERVAL` values (16 bytes each).
/// - `idx` must be within bounds of the vector.
///
/// # Pitfall P8
///
/// The `INTERVAL` struct is 16 bytes: `{ months: i32, days: i32, micros: i64 }`.
/// This layout matches `duckdb_interval` in `DuckDB`'s C headers.
///
/// # Example
///
/// ```rust
/// use quack_rs::interval::{read_interval_at, DuckInterval};
///
/// let ivs = [DuckInterval { months: 2, days: 15, micros: 1_000 }];
/// let data = ivs.as_ptr() as *const u8;
/// let read = unsafe { read_interval_at(data, 0) };
/// assert_eq!(read.months, 2);
/// assert_eq!(read.days, 15);
/// assert_eq!(read.micros, 1_000);
/// ```
#[inline]
pub const unsafe fn read_interval_at(data: *const u8, idx: usize) -> DuckInterval {
    // SAFETY: Each INTERVAL is exactly 16 bytes (repr(C) struct with i32, i32, i64).
    // The caller guarantees `data` points to valid INTERVAL data and `idx` is in bounds.
    let ptr = unsafe { data.add(idx * 16) };
    let months = unsafe { core::ptr::read_unaligned(ptr.cast::<i32>()) };
    let days = unsafe { core::ptr::read_unaligned(ptr.add(4).cast::<i32>()) };
    let micros = unsafe { core::ptr::read_unaligned(ptr.add(8).cast::<i64>()) };
    DuckInterval {
        months,
        days,
        micros,
    }
}

/// Asserts the size and alignment of [`DuckInterval`] match `DuckDB`'s C struct.
const _: () = {
    assert!(
        core::mem::size_of::<DuckInterval>() == 16,
        "DuckInterval must be exactly 16 bytes"
    );
    assert!(
        core::mem::align_of::<DuckInterval>() >= 4,
        "DuckInterval must have at least 4-byte alignment"
    );
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn size_of_duck_interval() {
        assert_eq!(core::mem::size_of::<DuckInterval>(), 16);
    }

    #[test]
    fn zero_interval() {
        let iv = DuckInterval::zero();
        assert_eq!(interval_to_micros(iv), Some(0));
    }

    #[test]
    fn default_interval() {
        let iv = DuckInterval::default();
        assert_eq!(iv, DuckInterval::zero());
    }

    #[test]
    fn one_day() {
        let iv = DuckInterval {
            months: 0,
            days: 1,
            micros: 0,
        };
        assert_eq!(interval_to_micros(iv), Some(MICROS_PER_DAY));
    }

    #[test]
    fn one_month() {
        let iv = DuckInterval {
            months: 1,
            days: 0,
            micros: 0,
        };
        assert_eq!(interval_to_micros(iv), Some(MICROS_PER_MONTH));
    }

    #[test]
    fn combined_interval() {
        let iv = DuckInterval {
            months: 0,
            days: 1,
            micros: 500_000,
        };
        let expected = MICROS_PER_DAY + 500_000;
        assert_eq!(interval_to_micros(iv), Some(expected));
    }

    #[test]
    fn negative_interval() {
        let iv = DuckInterval {
            months: -1,
            days: 0,
            micros: 0,
        };
        assert_eq!(interval_to_micros(iv), Some(-MICROS_PER_MONTH));
    }

    #[test]
    fn overflow_returns_none() {
        let iv = DuckInterval {
            months: i32::MAX,
            days: i32::MAX,
            micros: i64::MAX,
        };
        assert_eq!(interval_to_micros(iv), None);
    }

    #[test]
    fn saturating_on_overflow() {
        let iv = DuckInterval {
            months: i32::MAX,
            days: i32::MAX,
            micros: i64::MAX,
        };
        assert_eq!(interval_to_micros_saturating(iv), i64::MAX);
    }

    #[test]
    fn saturating_no_overflow() {
        let iv = DuckInterval {
            months: 0,
            days: 0,
            micros: 42,
        };
        assert_eq!(interval_to_micros_saturating(iv), 42);
    }

    #[test]
    fn to_micros_method() {
        let iv = DuckInterval {
            months: 0,
            days: 0,
            micros: 12345,
        };
        assert_eq!(iv.to_micros(), Some(12345));
    }

    #[test]
    fn to_micros_saturating_method() {
        let iv = DuckInterval {
            months: 0,
            days: 0,
            micros: 12345,
        };
        assert_eq!(iv.to_micros_saturating(), 12345);
    }

    #[test]
    fn read_interval_at_basic() {
        let data = [
            DuckInterval {
                months: 2,
                days: 15,
                micros: 999_000,
            },
            DuckInterval {
                months: -1,
                days: 3,
                micros: 0,
            },
        ];
        // SAFETY: data is a valid array of DuckInterval, idx 0 and 1 are in bounds.
        let iv0 = unsafe { read_interval_at(data.as_ptr().cast::<u8>(), 0) };
        assert_eq!(iv0.months, 2);
        assert_eq!(iv0.days, 15);
        assert_eq!(iv0.micros, 999_000);

        let iv1 = unsafe { read_interval_at(data.as_ptr().cast::<u8>(), 1) };
        assert_eq!(iv1.months, -1);
        assert_eq!(iv1.days, 3);
        assert_eq!(iv1.micros, 0);
    }

    #[test]
    fn exactly_max_i64_micros_no_overflow() {
        // If all overflow is in micros only (months=0, days=0), no overflow
        let iv = DuckInterval {
            months: 0,
            days: 0,
            micros: i64::MAX,
        };
        assert_eq!(interval_to_micros(iv), Some(i64::MAX));
    }

    #[test]
    fn months_calculation() {
        // 12 months = 12 * 30 days * 86400 * 1_000_000 us
        let iv = DuckInterval {
            months: 12,
            days: 0,
            micros: 0,
        };
        let expected = 12_i64 * MICROS_PER_MONTH;
        assert_eq!(interval_to_micros(iv), Some(expected));
    }

    // Mixed-sign overflow saturation tests (CRIT-5 regression tests)

    #[test]
    fn saturating_positive_overflow_with_negative_days() {
        // months = i32::MAX overflows to massive positive; days = -1 is tiny negative.
        // True result is still massively positive → should saturate to i64::MAX.
        let iv = DuckInterval {
            months: i32::MAX,
            days: -1,
            micros: 0,
        };
        assert_eq!(interval_to_micros(iv), None); // confirm it overflows
        assert_eq!(interval_to_micros_saturating(iv), i64::MAX);
    }

    #[test]
    fn saturating_negative_overflow_with_positive_days() {
        // months = i32::MIN overflows to massive negative; days = 1 is tiny positive.
        // True result is still massively negative → should saturate to i64::MIN.
        let iv = DuckInterval {
            months: i32::MIN,
            days: 1,
            micros: 0,
        };
        assert_eq!(interval_to_micros(iv), None);
        assert_eq!(interval_to_micros_saturating(iv), i64::MIN);
    }

    #[test]
    fn saturating_positive_overflow_negative_micros() {
        // Months alone overflow positive; negative micros doesn't change sign.
        let iv = DuckInterval {
            months: i32::MAX,
            days: 0,
            micros: -1_000_000,
        };
        assert_eq!(interval_to_micros(iv), None);
        assert_eq!(interval_to_micros_saturating(iv), i64::MAX);
    }

    #[test]
    fn saturating_negative_overflow_all_negative() {
        let iv = DuckInterval {
            months: i32::MIN,
            days: i32::MIN,
            micros: i64::MIN,
        };
        assert_eq!(interval_to_micros(iv), None);
        assert_eq!(interval_to_micros_saturating(iv), i64::MIN);
    }

    mod proptest_interval {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn micros_only_never_overflows_within_i64(micros: i64) {
                let iv = DuckInterval { months: 0, days: 0, micros };
                // micros-only interval always succeeds (no multiplication needed)
                assert_eq!(interval_to_micros(iv), Some(micros));
            }

            #[test]
            fn saturating_never_panics(months: i32, days: i32, micros: i64) {
                let iv = DuckInterval { months, days, micros };
                // Must not panic for any input
                let _ = interval_to_micros_saturating(iv);
            }

            #[test]
            fn saturating_direction_matches_i128(months: i32, days: i32, micros: i64) {
                let iv = DuckInterval { months, days, micros };
                let sat = interval_to_micros_saturating(iv);
                if interval_to_micros(iv).is_none() {
                    // Verify saturation direction using i128 ground truth
                    let total = i128::from(months) * i128::from(MICROS_PER_MONTH)
                        + i128::from(days) * i128::from(MICROS_PER_DAY)
                        + i128::from(micros);
                    if total >= 0 {
                        prop_assert_eq!(sat, i64::MAX);
                    } else {
                        prop_assert_eq!(sat, i64::MIN);
                    }
                }
            }

            #[test]
            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) {
                let iv = DuckInterval { months, days, micros };
                if let Some(checked) = interval_to_micros(iv) {
                    assert_eq!(interval_to_micros_saturating(iv), checked);
                }
            }
        }
    }
}