quack_rs/datetime/mod.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//! Calendar conversions for `DuckDB`'s temporal types.
7//!
8//! `VectorReader`/`VectorWriter` move `DATE`, `TIME` and `TIMESTAMP` as the raw
9//! integers `DuckDB` stores: days since 1970-01-01, microseconds since midnight,
10//! microseconds since the epoch. Turning those into year/month/day means
11//! implementing the proleptic Gregorian calendar — including `DuckDB`'s
12//! infinity sentinels — which is exactly the kind of thing an extension should
13//! not be reimplementing.
14//!
15//! `DuckDB` already exposes the conversions (`duckdb_from_date`,
16//! `duckdb_to_date`, `duckdb_from_time`, `duckdb_from_timestamp`, …) and they
17//! sit in the **stable** prefix of the C extension API, so they work on every
18//! release from v1.2.0 onwards and need no feature flag. This module wraps them
19//! in plain Rust structs.
20//!
21//! Using `DuckDB`'s own routines also means the results agree with `DuckDB`'s
22//! SQL semantics exactly, rather than approximately.
23//!
24//! # Example
25//!
26//! ```rust,no_run
27//! use quack_rs::datetime;
28//!
29//! // Inside a callback, given a DATE read as days-since-epoch:
30//! # let days = 0_i32;
31//! let date = unsafe { datetime::date_from_days(days) };
32//! assert_eq!((date.year, date.month, date.day), (1970, 1, 1));
33//!
34//! // …and back again. Composing can fail (a month of 13, a 30th of
35//! // February), so it returns an `Option`.
36//! assert_eq!(unsafe { datetime::date_to_days(date) }, Some(days));
37//! ```
38//!
39//! # Invalid input returns `None`, never aborts
40//!
41//! Several of `DuckDB`'s conversions throw a C++ exception on bad input — a
42//! `DATE` of 2026-13-01, decomposing the `infinity` `TIMESTAMP` — and the C API
43//! does not catch it, so it would abort the whole process. The wrappers here
44//! check first, mirroring `DuckDB`'s own conditions, and return `None`:
45//! [`date_to_days`], [`time_from_micros`], [`time_tz_from_bits`],
46//! [`timestamp_from_micros`], [`timestamp_to_micros`], [`time_tz_bits`] and
47//! [`decimal_to_f64`]. [`is_valid_date`] exposes the date check on its own.
48//! Two of those (`time_from_micros`, `time_tz_from_bits`) guard a debug
49//! assertion rather than an exception: a release build of `DuckDB` returns
50//! nonsense fields there, and a build with assertions aborts.
51//!
52//! # Infinity
53//!
54//! `DuckDB` reserves two values of `DATE` and of `TIMESTAMP` for `infinity` and
55//! `-infinity`. Decomposing one of those into a calendar date is meaningless, so
56//! check with [`is_finite_date`] / [`is_finite_timestamp`] first, or compare
57//! against the constants below.
58//!
59//! Note the exact values: negative infinity is `-i32::MAX` / `-i64::MAX`, **not**
60//! `i32::MIN` / `i64::MIN`. `i32::MIN` is an ordinary (if absurd) finite date.
61
62use libduckdb_sys::{
63 duckdb_date, duckdb_date_struct, duckdb_decimal, duckdb_decimal_to_double,
64 duckdb_double_to_decimal, duckdb_double_to_hugeint, duckdb_double_to_uhugeint,
65 duckdb_from_date, duckdb_from_time, duckdb_from_time_tz, duckdb_from_timestamp, duckdb_hugeint,
66 duckdb_hugeint_to_double, duckdb_is_finite_date, duckdb_is_finite_timestamp,
67 duckdb_is_finite_timestamp_ms, duckdb_is_finite_timestamp_ns, duckdb_is_finite_timestamp_s,
68 duckdb_time, duckdb_time_struct, duckdb_time_tz, duckdb_timestamp, duckdb_timestamp_ms,
69 duckdb_timestamp_ns, duckdb_timestamp_s, duckdb_timestamp_struct, duckdb_to_date,
70 duckdb_to_time, duckdb_to_timestamp, duckdb_uhugeint, duckdb_uhugeint_to_double,
71};
72
73mod checks;
74#[cfg(test)]
75mod tests;
76
77pub use checks::{is_valid_date, DECIMAL_MAX_WIDTH, MICROS_PER_DAY, TIME_TZ_MAX_OFFSET_SECONDS};
78
79/// A calendar date, as `DuckDB` decomposes a `DATE`.
80///
81/// `month` is 1–12 and `day` is 1–31; `year` may be negative (BCE).
82#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
83pub struct Date {
84 /// Proleptic Gregorian year. Negative values are BCE.
85 pub year: i32,
86 /// Month of year, 1–12.
87 pub month: i8,
88 /// Day of month, 1–31.
89 pub day: i8,
90}
91
92/// A wall-clock time, as `DuckDB` decomposes a `TIME`.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
94pub struct Time {
95 /// Hour of day, 0–23; 24 only in `24:00:00`, which `DuckDB` allows as a
96 /// `TIME`.
97 pub hour: i8,
98 /// Minute of hour, 0–59.
99 pub min: i8,
100 /// Second of minute, 0–59.
101 pub sec: i8,
102 /// Microseconds within the second, 0–999999.
103 pub micros: i32,
104}
105
106/// A `TIME WITH TIME ZONE`, decomposed into wall-clock time plus UTC offset.
107///
108/// The derived ordering is structural (wall-clock time first, then offset),
109/// not `DuckDB`'s SQL ordering, which compares the UTC instant.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
111pub struct TimeTz {
112 /// The wall-clock time.
113 pub time: Time,
114 /// Offset from UTC in seconds.
115 pub offset_seconds: i32,
116}
117
118/// A `TIMESTAMP`, decomposed into date and time parts.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
120pub struct Timestamp {
121 /// The calendar date.
122 pub date: Date,
123 /// The wall-clock time.
124 pub time: Time,
125}
126
127impl From<duckdb_date_struct> for Date {
128 fn from(value: duckdb_date_struct) -> Self {
129 Self {
130 year: value.year,
131 month: value.month,
132 day: value.day,
133 }
134 }
135}
136
137impl From<Date> for duckdb_date_struct {
138 fn from(value: Date) -> Self {
139 Self {
140 year: value.year,
141 month: value.month,
142 day: value.day,
143 }
144 }
145}
146
147impl From<duckdb_time_struct> for Time {
148 fn from(value: duckdb_time_struct) -> Self {
149 Self {
150 hour: value.hour,
151 min: value.min,
152 sec: value.sec,
153 micros: value.micros,
154 }
155 }
156}
157
158impl From<Time> for duckdb_time_struct {
159 fn from(value: Time) -> Self {
160 Self {
161 hour: value.hour,
162 min: value.min,
163 sec: value.sec,
164 micros: value.micros,
165 }
166 }
167}
168
169/// The `DATE` value `DuckDB` uses for `infinity`, in days since 1970-01-01.
170///
171/// Matches `duckdb::date_t::infinity()`.
172pub const DATE_INFINITY_DAYS: i32 = i32::MAX;
173
174/// The `DATE` value `DuckDB` uses for `-infinity`, in days since 1970-01-01.
175///
176/// Matches `duckdb::date_t::ninfinity()`, which is `-i32::MAX` — one greater
177/// than `i32::MIN`, so `i32::MIN` itself is a finite date.
178pub const DATE_NEGATIVE_INFINITY_DAYS: i32 = -i32::MAX;
179
180/// The `TIMESTAMP` value `DuckDB` uses for `infinity`, in microseconds since the
181/// epoch.
182///
183/// Matches `duckdb::timestamp_t::infinity()`.
184pub const TIMESTAMP_INFINITY_MICROS: i64 = i64::MAX;
185
186/// The `TIMESTAMP` value `DuckDB` uses for `-infinity`, in microseconds since
187/// the epoch.
188///
189/// Matches `duckdb::timestamp_t::ninfinity()`, which is `-i64::MAX`.
190pub const TIMESTAMP_NEGATIVE_INFINITY_MICROS: i64 = -i64::MAX;
191
192// ─── DATE ────────────────────────────────────────────────────────────────────
193
194/// Decomposes a `DATE` (days since 1970-01-01) into a calendar date.
195///
196/// Check [`is_finite_date`] first: `DuckDB` reserves extreme values for
197/// `infinity` / `-infinity`, which have no calendar representation.
198/// `duckdb_from_date` does not check for them — it cannot fail — so a
199/// sentinel decomposes into a date that looks real: `infinity` becomes
200/// 5881580-07-11, one day past the largest date `DuckDB` accepts.
201///
202/// # Safety
203///
204/// The `DuckDB` C API dispatch table must be initialised — it always is inside a
205/// callback or a registration closure.
206#[must_use]
207pub unsafe fn date_from_days(days: i32) -> Date {
208 // SAFETY: forwarded from this function's own contract.
209 unsafe { duckdb_from_date(duckdb_date { days }) }.into()
210}
211
212/// Composes a calendar date into a `DATE` (days since 1970-01-01).
213///
214/// Returns `None` if `DuckDB` cannot represent the date — a month outside
215/// 1–12, a day the month does not have, or a year beyond `DuckDB`'s range; see
216/// [`is_valid_date`]. `DuckDB` throws on such a date, which would abort the
217/// process, so it is checked here first.
218///
219/// # Safety
220///
221/// See [`date_from_days`].
222#[must_use]
223pub unsafe fn date_to_days(date: Date) -> Option<i32> {
224 if !is_valid_date(date) {
225 return None;
226 }
227 // SAFETY: forwarded from this function's own contract; the date passed
228 // `Date::IsValid`, so `Date::FromDate` does not throw.
229 Some(unsafe { duckdb_to_date(date.into()) }.days)
230}
231
232/// Returns `false` for `DuckDB`'s `infinity` / `-infinity` `DATE` sentinels.
233///
234/// # Safety
235///
236/// See [`date_from_days`].
237#[must_use]
238pub unsafe fn is_finite_date(days: i32) -> bool {
239 // SAFETY: forwarded from this function's own contract.
240 unsafe { duckdb_is_finite_date(duckdb_date { days }) }
241}
242
243// ─── TIME ────────────────────────────────────────────────────────────────────
244
245/// Decomposes a `TIME` (microseconds since midnight) into a wall-clock time.
246///
247/// Returns `None` outside `DuckDB`'s `TIME` range, 0 to [`MICROS_PER_DAY`]
248/// (`00:00:00`–`24:00:00`). `duckdb_from_time` does not check the range: a
249/// release build of `DuckDB` decomposes such a value into out-of-range fields
250/// (`-1` gives `micros == -1`), and a build with assertions enabled aborts the
251/// process, so it is checked here first.
252///
253/// # Safety
254///
255/// See [`date_from_days`].
256#[must_use]
257pub unsafe fn time_from_micros(micros: i64) -> Option<Time> {
258 if !checks::time_decomposes(micros) {
259 return None;
260 }
261 // SAFETY: forwarded from this function's own contract; `micros` is in
262 // `Time::IsValidTime`'s range, so `Time::Convert`'s assertion holds.
263 Some(unsafe { duckdb_from_time(duckdb_time { micros }) }.into())
264}
265
266/// Composes a wall-clock time into a `TIME` (microseconds since midnight).
267///
268/// Like `DuckDB`, this does not range-check the fields: it computes
269/// `((hour * 60 + min) * 60 + sec) * 1_000_000 + micros`, so an out-of-range
270/// field gives an out-of-range `TIME` rather than an error. It cannot throw.
271///
272/// # Safety
273///
274/// See [`date_from_days`].
275#[must_use]
276pub unsafe fn time_to_micros(time: Time) -> i64 {
277 // SAFETY: forwarded from this function's own contract.
278 unsafe { duckdb_to_time(time.into()) }.micros
279}
280
281/// Packs a wall-clock time and UTC offset into `DuckDB`'s `TIME WITH TIME ZONE`
282/// bit representation.
283///
284/// `offset_seconds` is the offset from UTC in seconds.
285///
286/// Returns `None` unless `micros_since_midnight` is between 0 and
287/// [`MICROS_PER_DAY`] inclusive (`00:00:00`–`24:00:00`) and `offset_seconds` within
288/// ±[`TIME_TZ_MAX_OFFSET_SECONDS`] (±15:59:59). `DuckDB` packs the two fields
289/// without checking either, so a value outside those ranges would silently
290/// corrupt the other field.
291///
292/// # Safety
293///
294/// See [`date_from_days`].
295#[must_use]
296pub unsafe fn time_tz_bits(micros_since_midnight: i64, offset_seconds: i32) -> Option<u64> {
297 if !checks::time_tz_encodable(micros_since_midnight, offset_seconds) {
298 return None;
299 }
300 // SAFETY: forwarded from this function's own contract.
301 Some(
302 unsafe { libduckdb_sys::duckdb_create_time_tz(micros_since_midnight, offset_seconds) }.bits,
303 )
304}
305
306/// Unpacks `DuckDB`'s `TIME WITH TIME ZONE` bit representation.
307///
308/// Returns `None` unless `bits` is an encoding [`time_tz_bits`] can produce:
309/// a time of day between `00:00:00` and `24:00:00` and an offset within
310/// ±[`TIME_TZ_MAX_OFFSET_SECONDS`]. The 40-bit time field can hold about 12.7
311/// days; `duckdb_from_time_tz` decomposes it with `Time::Convert`, whose
312/// assertion aborts a `DuckDB` built with assertions on anything past a day
313/// (see [`time_from_micros`]).
314///
315/// # Safety
316///
317/// See [`date_from_days`].
318#[must_use]
319pub unsafe fn time_tz_from_bits(bits: u64) -> Option<TimeTz> {
320 // `dtime_tz_t`: the time in the high 40 bits, `MAX_OFFSET - offset` in
321 // the low 24; both fit their targets without loss.
322 #[allow(clippy::cast_possible_wrap, reason = "40 bits fit an i64")]
323 let micros = (bits >> 24) as i64;
324 #[allow(clippy::cast_possible_truncation, reason = "24 bits fit an i32")]
325 let offset_seconds = TIME_TZ_MAX_OFFSET_SECONDS - (bits & 0x00FF_FFFF) as i32;
326 if !checks::time_tz_encodable(micros, offset_seconds) {
327 return None;
328 }
329 // SAFETY: forwarded from this function's own contract; the time field is
330 // in `Time::IsValidTime`'s range, so `Time::Convert`'s assertion holds.
331 let raw = unsafe { duckdb_from_time_tz(duckdb_time_tz { bits }) };
332 Some(TimeTz {
333 time: raw.time.into(),
334 offset_seconds: raw.offset,
335 })
336}
337
338// ─── TIMESTAMP ───────────────────────────────────────────────────────────────
339
340/// Decomposes a `TIMESTAMP` (microseconds since the epoch) into date and time.
341///
342/// Returns `None` for the `infinity` / `-infinity` sentinels (see
343/// [`is_finite_timestamp`]) and for the finite values below
344/// day `-106_751_991` (that many times [`MICROS_PER_DAY`]; the first ~4 hours of the `i64` range,
345/// including `i64::MIN`), whose day overflows when `DuckDB` multiplies it back
346/// into microseconds. `DuckDB` throws on all of them, which would abort the
347/// process, so they are checked here first.
348///
349/// # Safety
350///
351/// See [`date_from_days`].
352#[must_use]
353pub unsafe fn timestamp_from_micros(micros: i64) -> Option<Timestamp> {
354 if !checks::timestamp_decomposes(micros) {
355 return None;
356 }
357 // SAFETY: forwarded from this function's own contract; the check above
358 // rules out every input on which `Timestamp::Convert` throws.
359 let raw: duckdb_timestamp_struct =
360 unsafe { duckdb_from_timestamp(duckdb_timestamp { micros }) };
361 Some(Timestamp {
362 date: raw.date.into(),
363 time: raw.time.into(),
364 })
365}
366
367/// Composes date and time into a `TIMESTAMP` (microseconds since the epoch).
368///
369/// Returns `None` if the date is invalid (see [`is_valid_date`]), if the
370/// result overflows an `i64`, or if it would equal one of the infinity
371/// sentinels — every case in which `DuckDB` throws, which would abort the
372/// process. The time fields are not range-checked, exactly as in
373/// [`time_to_micros`].
374///
375/// # Safety
376///
377/// See [`date_from_days`].
378#[must_use]
379pub unsafe fn timestamp_to_micros(timestamp: Timestamp) -> Option<i64> {
380 // SAFETY: forwarded from this function's own contract.
381 let days = unsafe { date_to_days(timestamp.date) }?;
382 checks::timestamp_from_parts(days, checks::time_micros(timestamp.time))?;
383 let raw = duckdb_timestamp_struct {
384 date: timestamp.date.into(),
385 time: timestamp.time.into(),
386 };
387 // SAFETY: forwarded from this function's own contract; the checks above
388 // mirror every throw in `Date::FromDate` and `Timestamp::FromDatetime`.
389 Some(unsafe { duckdb_to_timestamp(raw) }.micros)
390}
391
392/// Returns `false` for `DuckDB`'s `infinity` / `-infinity` `TIMESTAMP`
393/// sentinels.
394///
395/// # Safety
396///
397/// See [`date_from_days`].
398#[must_use]
399pub unsafe fn is_finite_timestamp(micros: i64) -> bool {
400 // SAFETY: forwarded from this function's own contract.
401 unsafe { duckdb_is_finite_timestamp(duckdb_timestamp { micros }) }
402}
403
404/// `TIMESTAMP_S` variant of [`is_finite_timestamp`].
405///
406/// # Safety
407///
408/// See [`date_from_days`].
409#[must_use]
410pub unsafe fn is_finite_timestamp_s(seconds: i64) -> bool {
411 // SAFETY: forwarded from this function's own contract.
412 unsafe { duckdb_is_finite_timestamp_s(duckdb_timestamp_s { seconds }) }
413}
414
415/// `TIMESTAMP_MS` variant of [`is_finite_timestamp`].
416///
417/// # Safety
418///
419/// See [`date_from_days`].
420#[must_use]
421pub unsafe fn is_finite_timestamp_ms(millis: i64) -> bool {
422 // SAFETY: forwarded from this function's own contract.
423 unsafe { duckdb_is_finite_timestamp_ms(duckdb_timestamp_ms { millis }) }
424}
425
426/// `TIMESTAMP_NS` variant of [`is_finite_timestamp`].
427///
428/// # Safety
429///
430/// See [`date_from_days`].
431#[must_use]
432pub unsafe fn is_finite_timestamp_ns(nanos: i64) -> bool {
433 // SAFETY: forwarded from this function's own contract.
434 unsafe { duckdb_is_finite_timestamp_ns(duckdb_timestamp_ns { nanos }) }
435}
436
437// ─── Wide integers and DECIMAL ───────────────────────────────────────────────
438
439/// Converts a `HUGEINT` to `f64` the way `DuckDB` does.
440///
441/// # Safety
442///
443/// See [`date_from_days`].
444#[must_use]
445pub unsafe fn hugeint_to_f64(value: i128) -> f64 {
446 let raw = duckdb_hugeint {
447 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
448 lower: value as u64,
449 #[allow(clippy::cast_possible_truncation)]
450 upper: (value >> 64) as i64,
451 };
452 // SAFETY: forwarded from this function's own contract.
453 unsafe { duckdb_hugeint_to_double(raw) }
454}
455
456/// Converts an `f64` to `HUGEINT` the way `DuckDB` does, truncating toward
457/// zero.
458///
459/// A value `DuckDB` cannot convert — NaN, an infinity, or a value outside
460/// `(-2^127, 2^127)` — comes back as `0`, indistinguishable from a real zero
461/// (SQL's `CAST` raises an error instead). Use
462/// [`try_f64_to_hugeint`] to tell the two apart.
463///
464/// # Safety
465///
466/// See [`date_from_days`].
467#[must_use]
468pub unsafe fn f64_to_hugeint(value: f64) -> i128 {
469 // SAFETY: forwarded from this function's own contract.
470 let raw = unsafe { duckdb_double_to_hugeint(value) };
471 (i128::from(raw.upper) << 64) | i128::from(raw.lower)
472}
473
474/// Converts an `f64` to `HUGEINT` like [`f64_to_hugeint`], or `None` when
475/// `DuckDB` cannot convert it: NaN, an infinity, or a value outside
476/// `(-2^127, 2^127)`.
477///
478/// The bounds are the ones `DuckDB`'s `ConvertFloatingToBigint` applies
479/// (`hugeint.cpp`), checked here before the call.
480///
481/// # Safety
482///
483/// See [`date_from_days`].
484#[must_use]
485pub unsafe fn try_f64_to_hugeint(value: f64) -> Option<i128> {
486 // 2^127 is exactly representable; DuckDB compares against it (its
487 // `2^127 - 1` literal rounds to the same double).
488 const LIMIT: f64 = 170_141_183_460_469_231_731_687_303_715_884_105_728.0;
489 if !value.is_finite() || value <= -LIMIT || value >= LIMIT {
490 return None;
491 }
492 // SAFETY: forwarded from this function's own contract.
493 Some(unsafe { f64_to_hugeint(value) })
494}
495
496/// Converts a `UHUGEINT` to `f64` the way `DuckDB` does.
497///
498/// # Safety
499///
500/// See [`date_from_days`].
501#[must_use]
502pub unsafe fn uhugeint_to_f64(value: u128) -> f64 {
503 let raw = duckdb_uhugeint {
504 #[allow(clippy::cast_possible_truncation)]
505 lower: value as u64,
506 #[allow(clippy::cast_possible_truncation)]
507 upper: (value >> 64) as u64,
508 };
509 // SAFETY: forwarded from this function's own contract.
510 unsafe { duckdb_uhugeint_to_double(raw) }
511}
512
513/// Converts an `f64` to `UHUGEINT` the way `DuckDB` does, truncating toward
514/// zero.
515///
516/// A value `DuckDB` cannot convert — NaN, an infinity, a negative value, or
517/// one at or above `2^128` — comes back as `0`, indistinguishable from a real
518/// zero. Use [`try_f64_to_uhugeint`] to tell the two apart.
519///
520/// # Safety
521///
522/// See [`date_from_days`].
523#[must_use]
524pub unsafe fn f64_to_uhugeint(value: f64) -> u128 {
525 // SAFETY: forwarded from this function's own contract.
526 let raw = unsafe { duckdb_double_to_uhugeint(value) };
527 (u128::from(raw.upper) << 64) | u128::from(raw.lower)
528}
529
530/// Converts an `f64` to `UHUGEINT` like [`f64_to_uhugeint`], or `None` when
531/// `DuckDB` cannot convert it: NaN, an infinity, a negative value, or one at
532/// or above `2^128`.
533///
534/// The bounds are the ones `DuckDB`'s `ConvertFloatingToUhugeint` applies
535/// (`uhugeint.cpp`), checked here before the call. `-0.0` converts to `0`.
536///
537/// # Safety
538///
539/// See [`date_from_days`].
540#[must_use]
541pub unsafe fn try_f64_to_uhugeint(value: f64) -> Option<u128> {
542 const LIMIT: f64 = 340_282_366_920_938_463_463_374_607_431_768_211_456.0;
543 // A NaN is in no range, so `contains` refuses it as well as infinities.
544 if !(0.0..LIMIT).contains(&value) {
545 return None;
546 }
547 // SAFETY: forwarded from this function's own contract.
548 Some(unsafe { f64_to_uhugeint(value) })
549}
550
551/// A `DECIMAL` value: an unscaled `i128` plus its declared width and scale.
552///
553/// The derived ordering is structural (width, then scale, then the unscaled
554/// value), not numeric: `1.00` as `DECIMAL(5,2)` sorts above `2` as
555/// `DECIMAL(3,0)`. Compare values of one width and scale, or convert first.
556#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
557pub struct Decimal {
558 /// Total number of significant digits.
559 pub width: u8,
560 /// Number of digits after the decimal point.
561 pub scale: u8,
562 /// The unscaled value: the represented number is `value / 10^scale`.
563 pub value: i128,
564}
565
566/// Converts an `f64` into a `DECIMAL` of the given width and scale.
567///
568/// When `DuckDB` cannot convert — the value does not fit `DECIMAL(width,
569/// scale)`, it is NaN or infinite, `width` exceeds 38, or `scale` exceeds
570/// `width` — the result is `Decimal { width: 0, scale: 0, value: 0 }`, not an
571/// error. Use [`try_f64_to_decimal`] to get `None` instead.
572///
573/// # Safety
574///
575/// See [`date_from_days`].
576#[must_use]
577pub unsafe fn f64_to_decimal(value: f64, width: u8, scale: u8) -> Decimal {
578 // SAFETY: forwarded from this function's own contract.
579 let raw = unsafe { duckdb_double_to_decimal(value, width, scale) };
580 Decimal {
581 width: raw.width,
582 scale: raw.scale,
583 value: (i128::from(raw.value.upper) << 64) | i128::from(raw.value.lower),
584 }
585}
586
587/// Converts an `f64` into a `DECIMAL(width, scale)` like [`f64_to_decimal`],
588/// or `None` when it cannot.
589///
590/// It cannot when the value does not fit, it is NaN or infinite, `width` is 0
591/// or exceeds 38, or `scale` exceeds `width`.
592///
593/// `DuckDB` signals a failed conversion by returning width 0; a successful
594/// one carries the requested width, so the two cannot be confused once a
595/// width of 0 is refused up front.
596///
597/// # Safety
598///
599/// See [`date_from_days`].
600#[must_use]
601pub unsafe fn try_f64_to_decimal(value: f64, width: u8, scale: u8) -> Option<Decimal> {
602 if !checks::decimal_is_valid(width, scale) {
603 return None;
604 }
605 // SAFETY: forwarded from this function's own contract.
606 let decimal = unsafe { f64_to_decimal(value, width, scale) };
607 (decimal.width == width).then_some(decimal)
608}
609
610/// Converts a `DECIMAL` to `f64` the way `DuckDB` does.
611///
612/// Returns `None` if `width` exceeds [`DECIMAL_MAX_WIDTH`] (38) or `scale`
613/// exceeds `width`. `DuckDB` indexes its powers-of-ten tables by `scale`
614/// without a bounds check, so such a scale reads past the table (returning
615/// `inf`, `NaN` or garbage).
616///
617/// # Safety
618///
619/// See [`date_from_days`].
620#[must_use]
621pub unsafe fn decimal_to_f64(decimal: Decimal) -> Option<f64> {
622 if !checks::decimal_is_valid(decimal.width, decimal.scale) {
623 return None;
624 }
625 let raw = duckdb_decimal {
626 width: decimal.width,
627 scale: decimal.scale,
628 value: duckdb_hugeint {
629 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
630 lower: decimal.value as u64,
631 #[allow(clippy::cast_possible_truncation)]
632 upper: (decimal.value >> 64) as i64,
633 },
634 };
635 // SAFETY: forwarded from this function's own contract; `scale <= 38`
636 // keeps DuckDB's table lookups in bounds.
637 Some(unsafe { duckdb_decimal_to_double(raw) })
638}