1use alloc::format;
13use alloc::string::{String, ToString};
14use alloc::vec::Vec;
15
16use super::{MONTH_ABBR, MONTH_FULL, civil_from_days};
17
18#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27pub enum DateOrder {
28 Mdy,
29 Dmy,
30 Ymd,
31}
32
33#[derive(Clone, Copy, PartialEq, Eq, Debug)]
34pub enum DateStyleKind {
35 Iso,
36 German,
37 Sql,
38 Postgres,
39}
40
41#[derive(Clone, Copy, PartialEq, Eq, Debug)]
42pub enum IntervalStyleKind {
43 Postgres,
44 SqlStandard,
45 Iso8601,
46 PostgresVerbose,
47}
48
49#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub struct RenderStyle {
51 pub date_style: DateStyleKind,
52 pub date_order: DateOrder,
53 pub interval_style: IntervalStyleKind,
54 pub extra_float_digits: i32,
57 pub bytea_escape: bool,
63 pub mysql: bool,
68}
69
70impl Default for RenderStyle {
71 fn default() -> Self {
72 Self {
73 date_style: DateStyleKind::Iso,
74 date_order: DateOrder::Mdy,
75 interval_style: IntervalStyleKind::Postgres,
76 extra_float_digits: 1,
77 bytea_escape: false,
78 mysql: false,
79 }
80 }
81}
82
83fn dow_abbr(days: i32) -> &'static str {
85 const DOW: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
86 DOW[((days.rem_euclid(7)) as usize + 3) % 7]
87}
88
89fn hms_from_day_micros(day_micros: i64) -> String {
92 let secs = day_micros / 1_000_000;
93 let frac = day_micros % 1_000_000;
94 let hh = secs / 3600;
95 let mm = (secs / 60) % 60;
96 let ss = secs % 60;
97 if frac == 0 {
98 format!("{hh:02}:{mm:02}:{ss:02}")
99 } else {
100 let raw = format!("{frac:06}");
101 let trimmed = raw.trim_end_matches('0');
102 format!("{hh:02}:{mm:02}:{ss:02}.{trimmed}")
103 }
104}
105
106pub fn format_date_styled(days: i32, style: &RenderStyle) -> String {
112 if days == i32::MAX {
113 return "infinity".into();
114 }
115 if days == i32::MIN {
116 return "-infinity".into();
117 }
118 let (y, m, d) = civil_from_days(days);
119 let (y, bc) = if y <= 0 { (1 - y, " BC") } else { (y, "") };
120 let dmy = style.date_order == DateOrder::Dmy;
121 match style.date_style {
122 DateStyleKind::Iso => format!("{y:04}-{m:02}-{d:02}{bc}"),
123 DateStyleKind::German => format!("{d:02}.{m:02}.{y:04}{bc}"),
124 DateStyleKind::Sql => {
125 if dmy {
126 format!("{d:02}/{m:02}/{y:04}{bc}")
127 } else {
128 format!("{m:02}/{d:02}/{y:04}{bc}")
129 }
130 }
131 DateStyleKind::Postgres => {
132 if dmy {
133 format!("{d:02}-{m:02}-{y:04}{bc}")
134 } else {
135 format!("{m:02}-{d:02}-{y:04}{bc}")
136 }
137 }
138 }
139}
140
141pub fn format_timestamp_styled(micros: i64, style: &RenderStyle) -> String {
145 if micros == i64::MAX {
146 return "infinity".into();
147 }
148 if micros == i64::MIN {
149 return "-infinity".into();
150 }
151 if style.date_style == DateStyleKind::Iso {
152 return format_timestamp(micros);
153 }
154 const MICROS_PER_DAY: i64 = 86_400_000_000;
155 let days = micros.div_euclid(MICROS_PER_DAY);
156 let day_micros = micros.rem_euclid(MICROS_PER_DAY);
157 let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
158 let hms = hms_from_day_micros(day_micros);
159 match style.date_style {
160 DateStyleKind::Iso => unreachable!("handled above"),
161 DateStyleKind::German | DateStyleKind::Sql => {
162 let d = format_date_styled(day_i32, style);
165 match d.strip_suffix(" BC") {
166 Some(base) => format!("{base} {hms} BC"),
167 None => format!("{d} {hms}"),
168 }
169 }
170 DateStyleKind::Postgres => {
171 let (y, m, d) = civil_from_days(day_i32);
172 let (y, bc) = if y <= 0 { (1 - y, " BC") } else { (y, "") };
173 let mon = MONTH_ABBR[(m as usize).saturating_sub(1).min(11)];
174 let dow = dow_abbr(day_i32);
175 if style.date_order == DateOrder::Dmy {
176 format!("{dow} {d} {mon} {hms} {y:04}{bc}")
177 } else {
178 format!("{dow} {mon} {d} {hms} {y:04}{bc}")
179 }
180 }
181 }
182}
183
184pub fn format_timestamptz_styled(micros: i64, style: &RenderStyle) -> String {
188 format_timestamptz_tz(micros, style, 0, None)
189}
190
191pub fn format_timestamptz_tz(
197 micros: i64,
198 style: &RenderStyle,
199 offset_micros: i64,
200 abbr: Option<&str>,
201) -> String {
202 if style.date_style == DateStyleKind::Iso {
203 return format_timestamptz_at(micros, offset_micros);
204 }
205 if micros == i64::MAX || micros == i64::MIN {
206 return format_timestamp(micros);
207 }
208 let body = format_timestamp_styled(micros + offset_micros, style);
209 match abbr {
210 Some(a) => format!("{body} {a}"),
211 None if offset_micros == 0 => format!("{body} UTC"),
212 None => {
213 let total_min = (offset_micros / 60_000_000).abs();
214 let (h, m) = (total_min / 60, total_min % 60);
215 let sign = if offset_micros < 0 { '-' } else { '+' };
216 if m == 0 {
217 format!("{body} {sign}{h:02}")
218 } else {
219 format!("{body} {sign}{h:02}:{m:02}")
220 }
221 }
222 }
223}
224
225fn sql_std_time(abs_us: i64) -> String {
228 let secs = abs_us / 1_000_000;
229 let frac = abs_us % 1_000_000;
230 let h = secs / 3600;
231 let mm = (secs / 60) % 60;
232 let ss = secs % 60;
233 if frac == 0 {
234 format!("{h}:{mm:02}:{ss:02}")
235 } else {
236 let raw = format!("{frac:06}");
237 let trimmed = raw.trim_end_matches('0');
238 format!("{h}:{mm:02}:{ss:02}.{trimmed}")
239 }
240}
241
242fn secs_body(abs_us: i64) -> String {
244 let ss = abs_us / 1_000_000;
245 let frac = abs_us % 1_000_000;
246 if frac == 0 {
247 format!("{ss}")
248 } else {
249 let raw = format!("{frac:06}");
250 let trimmed = raw.trim_end_matches('0');
251 format!("{ss}.{trimmed}")
252 }
253}
254
255#[must_use]
275pub fn format_interval_kinded(
276 months: i32,
277 days: i32,
278 micros: i64,
279 kind: spg_storage::IntervalKind,
280) -> String {
281 match kind {
282 spg_storage::IntervalKind::PosInf => alloc::string::String::from("infinity"),
283 spg_storage::IntervalKind::NegInf => alloc::string::String::from("-infinity"),
284 spg_storage::IntervalKind::Finite => format_interval(months, days, micros),
285 }
286}
287
288pub fn format_interval_styled(months: i32, days: i32, micros: i64, style: &RenderStyle) -> String {
289 match style.interval_style {
290 IntervalStyleKind::Postgres => format_interval(months, days, micros),
291 IntervalStyleKind::SqlStandard => {
292 let has_ym = months != 0;
293 let has_dt = days != 0 || micros != 0;
294 if !has_ym && !has_dt {
295 return "0".into();
296 }
297 let y = months / 12;
298 let mo = (months % 12).abs();
299 let signs: Vec<i8> = [i64::from(months), i64::from(days), micros]
303 .iter()
304 .filter(|v| **v != 0)
305 .map(|v| if *v < 0 { -1i8 } else { 1 })
306 .collect();
307 let coherent = signs.windows(2).all(|w| w[0] == w[1]);
308 if has_ym && !has_dt && coherent {
309 return format!("{y}-{mo}");
310 }
311 if !has_ym && coherent {
312 let neg = days < 0 || micros < 0;
313 let time = sql_std_time(micros.abs());
314 if days == 0 {
315 return format!("{}{time}", if neg { "-" } else { "" });
316 }
317 return format!("{days} {time}");
318 }
319 let sgn = |neg: bool| if neg { '-' } else { '+' };
322 format!(
323 "{}{}-{} {}{} {}{}",
324 sgn(months < 0),
325 y.abs(),
326 mo,
327 sgn(days < 0),
328 days.abs(),
329 sgn(micros < 0),
330 sql_std_time(micros.abs())
331 )
332 }
333 IntervalStyleKind::Iso8601 => {
334 if months == 0 && days == 0 && micros == 0 {
335 return "PT0S".into();
336 }
337 let y = months / 12;
338 let mo = months % 12;
339 let mut out = String::from("P");
340 if y != 0 {
341 out.push_str(&format!("{y}Y"));
342 }
343 if mo != 0 {
344 out.push_str(&format!("{mo}M"));
345 }
346 if days != 0 {
347 out.push_str(&format!("{days}D"));
348 }
349 if micros != 0 {
350 out.push('T');
351 let neg = micros < 0;
352 let abs = micros.abs();
353 let h = abs / 3_600_000_000;
354 let m = (abs / 60_000_000) % 60;
355 let s_us = abs % 60_000_000;
356 let sgn = if neg { "-" } else { "" };
357 if h != 0 {
358 out.push_str(&format!("{sgn}{h}H"));
359 }
360 if m != 0 {
361 out.push_str(&format!("{sgn}{m}M"));
362 }
363 if s_us != 0 {
364 out.push_str(&format!("{sgn}{}S", secs_body(s_us)));
365 }
366 }
367 out
368 }
369 IntervalStyleKind::PostgresVerbose => {
370 if months == 0 && days == 0 && micros == 0 {
371 return "@ 0".into();
372 }
373 let total = i128::from(months) * 30 * 86_400_000_000
377 + i128::from(days) * 86_400_000_000
378 + i128::from(micros);
379 let ago = total < 0;
380 let (months, days, micros) = if ago {
381 (-months, -days, -micros)
382 } else {
383 (months, days, micros)
384 };
385 let y = months / 12;
386 let mo = months % 12;
387 let neg_t = micros < 0;
388 let abs = micros.abs();
389 let h = abs / 3_600_000_000;
390 let m = (abs / 60_000_000) % 60;
391 let s_us = abs % 60_000_000;
392 let mut parts: Vec<String> = Vec::new();
393 let unit = |n: i64, singular: &'static str| -> String {
394 if n == 1 {
395 singular.into()
396 } else {
397 format!("{singular}s")
398 }
399 };
400 if y != 0 {
401 parts.push(format!("{y} {}", unit(i64::from(y), "year")));
402 }
403 if mo != 0 {
404 parts.push(format!("{mo} {}", unit(i64::from(mo), "mon")));
405 }
406 if days != 0 {
407 parts.push(format!("{days} {}", unit(i64::from(days), "day")));
408 }
409 let tsgn = if neg_t { "-" } else { "" };
410 if h != 0 {
411 parts.push(format!("{tsgn}{h} {}", unit(h, "hour")));
412 }
413 if m != 0 {
414 parts.push(format!("{tsgn}{m} {}", unit(m, "min")));
415 }
416 if s_us != 0 {
417 let body = secs_body(s_us);
418 let plural = body != "1";
419 parts.push(format!(
420 "{tsgn}{body} {}",
421 if plural { "secs" } else { "sec" }
422 ));
423 }
424 let mut out = String::from("@ ");
425 out.push_str(&parts.join(" "));
426 if ago {
427 out.push_str(" ago");
428 }
429 out
430 }
431 }
432}
433
434pub fn format_date_array_styled(items: &[Option<i32>], style: &RenderStyle) -> String {
436 array_styled(items, |d| format_date_styled(*d, style))
437}
438
439pub fn format_timestamp_array_styled(
440 items: &[Option<i64>],
441 with_tz: bool,
442 style: &RenderStyle,
443) -> String {
444 if with_tz {
445 array_styled(items, |t| format_timestamptz_styled(*t, style))
446 } else {
447 array_styled(items, |t| format_timestamp_styled(*t, style))
448 }
449}
450
451pub fn format_interval_array_styled(
452 items: &[Option<spg_storage::IntervalSpan>],
453 style: &RenderStyle,
454) -> String {
455 array_styled(items, |iv| {
456 if iv.kind.is_finite() {
457 format_interval_styled(iv.months, iv.days, iv.micros, style)
458 } else {
459 format_interval_kinded(0, 0, 0, iv.kind)
460 }
461 })
462}
463
464pub fn format_float_array_styled(items: &[Option<f64>], style: &RenderStyle) -> String {
465 array_styled(items, |f| format_float_styled(*f, style))
466}
467
468fn array_styled<T>(items: &[Option<T>], mut f: impl FnMut(&T) -> String) -> String {
469 let mut out = String::with_capacity(2 + items.len() * 12);
470 out.push('{');
471 for (i, item) in items.iter().enumerate() {
472 if i > 0 {
473 out.push(',');
474 }
475 match item {
476 None => out.push_str("NULL"),
477 Some(v) => push_array_element(&mut out, &f(v)),
478 }
479 }
480 out.push('}');
481 out
482}
483
484fn push_array_element(out: &mut String, s: &str) {
492 let needs_quote = s.is_empty()
493 || s.eq_ignore_ascii_case("null")
494 || s.chars()
495 .any(|c| matches!(c, ',' | '{' | '}' | '"' | '\\') || c.is_whitespace());
496 if !needs_quote {
497 out.push_str(s);
498 return;
499 }
500 out.push('"');
501 for c in s.chars() {
502 if c == '"' || c == '\\' {
503 out.push('\\');
504 }
505 out.push(c);
506 }
507 out.push('"');
508}
509
510fn format_g(x: f64, prec: usize) -> String {
515 let prec = prec.max(1);
516 let sci = format!("{:.*e}", prec - 1, x);
519 let epos = sci.find('e').expect("{:e} always has an 'e'");
520 let exp_val: i32 = sci[epos + 1..].parse().unwrap_or(0);
521 let mant = &sci[..epos];
522 if exp_val >= -4 && (exp_val as i64) < prec as i64 {
523 let decimals =
525 usize::try_from(i64::try_from(prec).unwrap_or(1) - 1 - i64::from(exp_val)).unwrap_or(0);
526 let rounded: f64 = sci.parse().unwrap_or(x);
527 let fixed = format!("{rounded:.decimals$}");
528 if fixed.contains('.') {
529 let t = fixed.trim_end_matches('0').trim_end_matches('.');
530 t.into()
531 } else {
532 fixed
533 }
534 } else {
535 let mant = if mant.contains('.') {
536 mant.trim_end_matches('0').trim_end_matches('.')
537 } else {
538 mant
539 };
540 let (sign, digits) = if exp_val < 0 {
541 ('-', format!("{}", -exp_val))
542 } else {
543 ('+', format!("{exp_val}"))
544 };
545 format!("{mant}e{sign}{digits:0>2}")
546 }
547}
548
549pub fn format_float_styled(x: f64, style: &RenderStyle) -> String {
552 if style.extra_float_digits >= 1 {
553 return format_float(x);
554 }
555 if x.is_nan() {
556 return "NaN".into();
557 }
558 if x.is_infinite() {
559 return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
560 }
561 if x == 0.0 {
562 return if x.is_sign_negative() { "-0" } else { "0" }.into();
563 }
564 let prec = (15 + style.extra_float_digits).clamp(1, 17) as usize;
565 format_g(x, prec)
566}
567
568pub fn format_real_styled(x: f32, style: &RenderStyle) -> String {
571 if style.extra_float_digits >= 1 {
572 return format_real(x);
573 }
574 if x.is_nan() {
575 return "NaN".into();
576 }
577 if x.is_infinite() {
578 return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
579 }
580 if x == 0.0 {
581 return if x.is_sign_negative() { "-0" } else { "0" }.into();
582 }
583 let prec = (6 + style.extra_float_digits).clamp(1, 9) as usize;
584 format_g(f64::from(x), prec)
585}
586
587pub fn format_date(days: i32) -> String {
590 if days == i32::MAX {
591 return "infinity".into();
592 }
593 if days == i32::MIN {
594 return "-infinity".into();
595 }
596 let (y, m, d) = civil_from_days(days);
597 if y <= 0 {
600 return format!("{:04}-{m:02}-{d:02} BC", 1 - y);
601 }
602 format!("{y:04}-{m:02}-{d:02}")
603}
604
605pub fn format_timestamptz(micros: i64) -> String {
616 format_timestamptz_at(micros, 0)
617}
618
619pub fn format_timestamptz_at(micros: i64, offset_micros: i64) -> String {
624 if micros == i64::MAX || micros == i64::MIN {
625 return format_timestamp(micros);
626 }
627 let base = format_timestamp(micros + offset_micros);
628 let (base, bc) = match base.strip_suffix(" BC") {
631 Some(b) => (String::from(b), " BC"),
632 None => (base, ""),
633 };
634 let mut s = String::with_capacity(base.len() + 9);
635 s.push_str(&base);
636 let total_min = (offset_micros / 60_000_000).abs();
637 let (h, m) = (total_min / 60, total_min % 60);
638 s.push(if offset_micros < 0 { '-' } else { '+' });
639 s.push_str(&alloc::format!("{h:02}"));
640 if m != 0 {
641 s.push(':');
642 s.push_str(&alloc::format!("{m:02}"));
643 }
644 s.push_str(bc);
645 s
646}
647
648pub fn format_float(x: f64) -> String {
658 if x.is_nan() {
659 return "NaN".into();
660 }
661 if x.is_infinite() {
662 return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
663 }
664 if x == 0.0 {
665 return if x.is_sign_negative() { "-0" } else { "0" }.into();
666 }
667 let sci = shortest_float_sci(x); let epos = sci.find('e').expect("{:e} always has an 'e'");
669 let exp_val: i32 = sci[epos + 1..].parse().unwrap_or(0);
670 if (-4..=14).contains(&exp_val) {
671 return fixed_from_sci(&sci, exp_val);
674 }
675 let mant = &sci[..epos];
676 let exp = &sci[epos + 1..];
677 let (sign, digits) = match exp.strip_prefix('-') {
678 Some(d) => ('-', d),
679 None => ('+', exp),
680 };
681 alloc::format!("{mant}e{sign}{digits:0>2}")
682}
683
684fn shortest_real_sci(x: f32) -> String {
701 let wide = f64::from(x);
702 let below = f64::from(next_f32(x, false));
703 let above = f64::from(next_f32(x, true));
704 let lo = (wide + below) / 2.0;
706 let hi = (wide + above) / 2.0;
707 for p in 1..=9u32 {
708 let cand = alloc::format!("{x:.*e}", (p - 1) as usize);
709 let Ok(v) = cand.parse::<f64>() else { continue };
710 #[allow(clippy::cast_possible_truncation)]
712 if v as f32 == x && v != lo && v != hi {
713 return cand;
714 }
715 }
716 alloc::format!("{x:e}")
717}
718
719fn next_f32(x: f32, up: bool) -> f32 {
722 let bits = x.to_bits();
723 let stepped = if (x > 0.0) == up { bits + 1 } else { bits - 1 };
724 f32::from_bits(stepped)
725}
726
727fn fixed_from_sci(sci: &str, exp: i32) -> String {
729 let epos = sci.find('e').expect("{:e} always has an 'e'");
730 let (mant, _) = sci.split_at(epos);
731 let (sign, mant) = match mant.strip_prefix('-') {
732 Some(m) => ("-", m),
733 None => ("", mant),
734 };
735 let digits: String = mant.chars().filter(char::is_ascii_digit).collect();
736 let point = exp + 1; let mut out = String::from(sign);
738 if point <= 0 {
739 out.push_str("0.");
740 for _ in 0..-point {
741 out.push('0');
742 }
743 out.push_str(&digits);
744 } else if (point as usize) >= digits.len() {
745 out.push_str(&digits);
746 for _ in 0..(point as usize - digits.len()) {
747 out.push('0');
748 }
749 } else {
750 out.push_str(&digits[..point as usize]);
751 out.push('.');
752 out.push_str(&digits[point as usize..]);
753 }
754 out
755}
756
757pub fn format_real(x: f32) -> String {
762 if x.is_nan() {
763 return "NaN".into();
764 }
765 if x.is_infinite() {
766 return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
767 }
768 if x == 0.0 {
769 return if x.is_sign_negative() { "-0" } else { "0" }.into();
770 }
771 let sci = shortest_real_sci(x);
772 let epos = sci.find('e').expect("{:e} always has an 'e'");
773 let exp_val: i32 = sci[epos + 1..].parse().unwrap_or(0);
774 if (-4..=5).contains(&exp_val) {
775 return fixed_from_sci(&sci, exp_val);
779 }
780 let mant = &sci[..epos];
781 let exp = &sci[epos + 1..];
782 let (sign, digits) = match exp.strip_prefix('-') {
783 Some(d) => ('-', d),
784 None => ('+', exp),
785 };
786 alloc::format!("{mant}e{sign}{digits:0>2}")
787}
788
789pub fn format_money(cents: i64) -> String {
792 let neg = cents < 0;
793 let abs = cents.unsigned_abs();
794 let dollars = abs / 100;
795 let cc = abs % 100;
796 let dollar_str = dollars.to_string();
798 let bytes = dollar_str.as_bytes();
799 let mut int_part = String::with_capacity(dollar_str.len() + dollar_str.len() / 3);
800 for (i, b) in bytes.iter().enumerate() {
801 let from_right = bytes.len() - i;
804 if i > 0 && from_right % 3 == 0 {
805 int_part.push(',');
806 }
807 int_part.push(*b as char);
808 }
809 let sign = if neg { "-" } else { "" };
810 format!("{sign}${int_part}.{cc:02}")
811}
812
813pub fn format_timetz(us: i64, offset_secs: i32) -> String {
818 let time = format_time(us);
819 let sign = if offset_secs < 0 { '-' } else { '+' };
820 let abs = offset_secs.unsigned_abs();
821 let oh = abs / 3600;
822 let om = (abs % 3600) / 60;
823 if om == 0 {
824 format!("{time}{sign}{oh:02}")
825 } else {
826 format!("{time}{sign}{oh:02}:{om:02}")
827 }
828}
829
830pub fn format_time(us: i64) -> String {
835 let total_secs = us.div_euclid(1_000_000);
836 let frac = us.rem_euclid(1_000_000);
837 let hh = total_secs / 3600;
838 let mm = (total_secs / 60) % 60;
839 let ss = total_secs % 60;
840 if frac == 0 {
841 format!("{hh:02}:{mm:02}:{ss:02}")
842 } else {
843 let raw = format!("{frac:06}");
844 let trimmed = raw.trim_end_matches('0');
845 format!("{hh:02}:{mm:02}:{ss:02}.{trimmed}")
846 }
847}
848
849pub fn format_timestamp(micros: i64) -> String {
850 if micros == i64::MAX {
852 return "infinity".into();
853 }
854 if micros == i64::MIN {
855 return "-infinity".into();
856 }
857 const MICROS_PER_DAY: i64 = 86_400_000_000;
858 let days = micros.div_euclid(MICROS_PER_DAY);
861 let day_micros = micros.rem_euclid(MICROS_PER_DAY);
862 let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
863 let (y, m, d) = civil_from_days(day_i32);
864 let (y, bc) = if y <= 0 { (1 - y, " BC") } else { (y, "") };
866 let secs = day_micros / 1_000_000;
867 let frac = day_micros % 1_000_000;
868 let hh = secs / 3600;
869 let mm = (secs / 60) % 60;
870 let ss = secs % 60;
871 if frac == 0 {
872 format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}{bc}")
873 } else {
874 let raw = format!("{frac:06}");
876 let trimmed = raw.trim_end_matches('0');
877 format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}.{trimmed}{bc}")
878 }
879}
880
881#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
884pub fn days_from_civil(y: i32, m: u32, d: u32) -> i32 {
885 let y_adj = if m <= 2 {
886 i64::from(y) - 1
887 } else {
888 i64::from(y)
889 };
890 let era = y_adj.div_euclid(400);
891 let yoe = (y_adj - era * 400) as u32;
892 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d.saturating_sub(1);
893 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
894 let total = era * 146_097 + i64::from(doe) - 719_468;
895 i32::try_from(total).unwrap_or(i32::MAX)
896}
897
898pub fn parse_date_literal(s: &str) -> Option<i32> {
902 parse_date_literal_ordered(s, DateOrder::Mdy)
903}
904
905pub fn parse_date_literal_ordered(s: &str, order: DateOrder) -> Option<i32> {
915 let s = s.trim();
916 if let Some(base) = s
920 .strip_suffix(" BC")
921 .or_else(|| s.strip_suffix(" bc"))
922 .or_else(|| s.strip_suffix(" Bc"))
923 {
924 let days = parse_date_literal_ordered(base, order)?;
925 let (y, m, d) = civil_from_days(days);
926 if y < 1 {
927 return None;
928 }
929 return Some(days_from_civil(1 - y, m, d));
930 }
931 if let Some(base) = s.strip_suffix(" AD").or_else(|| s.strip_suffix(" ad")) {
932 return parse_date_literal_ordered(base, order);
933 }
934 if s.eq_ignore_ascii_case("epoch") {
936 return Some(days_from_civil(1970, 1, 1));
937 }
938 if s.eq_ignore_ascii_case("infinity") || s.eq_ignore_ascii_case("+infinity") {
939 return Some(i32::MAX);
940 }
941 if s.eq_ignore_ascii_case("-infinity") {
942 return Some(i32::MIN);
943 }
944 let bytes = s.as_bytes();
945 if bytes.len() == 8 && bytes.iter().all(u8::is_ascii_digit) {
947 let y: i32 = s[0..4].parse().ok()?;
948 let m: u32 = s[4..6].parse().ok()?;
949 let d: u32 = s[6..8].parse().ok()?;
950 if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
951 return None;
952 }
953 return Some(days_from_civil(y, m, d));
954 }
955 if s.bytes().any(|b| b.is_ascii_alphabetic()) {
960 if let Some(jd) = s.strip_prefix(['J', 'j'])
963 && !jd.is_empty()
964 && jd.bytes().all(|b| b.is_ascii_digit())
965 {
966 let jd: i64 = jd.parse().ok()?;
967 return i32::try_from(jd - 2_440_588).ok();
968 }
969 return parse_month_name_date(s, order);
970 }
971 {
978 let mut two = s.splitn(2, ['-', '/', '.']);
979 if let (Some(ya), Some(dd)) = (two.next(), two.next())
980 && ya.len() >= 3
981 && dd.len() == 3
982 && !dd.contains(['-', '/', '.', ' '])
983 && ya.bytes().all(|b| b.is_ascii_digit())
984 && dd.bytes().all(|b| b.is_ascii_digit())
985 {
986 let y: i32 = ya.parse().ok()?;
987 let doy: i64 = dd.parse().ok()?;
988 if y != 0 && (1..=366).contains(&doy) {
989 let jan1 = days_from_civil(y, 1, 1);
990 let days = jan1 + i32::try_from(doy).ok()? - 1;
991 let (yy, _, _) = civil_from_days(days);
992 if yy == y {
993 return Some(days);
994 }
995 return None; }
997 }
998 }
999 let mut parts = s.splitn(3, ['-', '/', '.']);
1000 let (fa, fb, fc) = (parts.next()?, parts.next()?, parts.next()?);
1001 if fc.contains(['-', '/', '.', ' ']) {
1002 return None; }
1004 if [fa, fb, fc]
1005 .iter()
1006 .any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()))
1007 {
1008 return None;
1009 }
1010 if fa.len() >= 3 && fb.len() <= 2 && fc.len() <= 2 {
1014 let y: i32 = fa.parse().ok()?;
1015 if y == 0 {
1017 return None;
1018 }
1019 let m: u32 = fb.parse().ok()?;
1023 let d: u32 = fc.parse().ok()?;
1024 if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
1028 return None;
1029 }
1030 return Some(days_from_civil(y, m, d));
1031 }
1032 let expand_year = |t: &str| -> Option<i32> {
1034 match t.len() {
1035 4 => t.parse().ok(),
1036 1 | 2 => {
1038 let n: i32 = t.parse().ok()?;
1039 Some(if n < 70 { 2000 + n } else { 1900 + n })
1040 }
1041 _ => None,
1042 }
1043 };
1044 let (ys, ms, ds) = match order {
1045 DateOrder::Mdy => (fc, fa, fb),
1046 DateOrder::Dmy => (fc, fb, fa),
1047 DateOrder::Ymd => (fa, fb, fc),
1048 };
1049 if ms.len() > 2 || ds.len() > 2 {
1050 return None;
1051 }
1052 let y = expand_year(ys)?;
1053 let m: u32 = ms.parse().ok()?;
1054 let d: u32 = ds.parse().ok()?;
1055 if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
1056 return None;
1057 }
1058 Some(days_from_civil(y, m, d))
1059}
1060
1061fn parse_month_name_date(s: &str, order: DateOrder) -> Option<i32> {
1068 let tokens: alloc::vec::Vec<&str> =
1069 s.split([' ', ',', '-']).filter(|t| !t.is_empty()).collect();
1070 if tokens.len() != 3 {
1071 return None;
1072 }
1073 let month_of = |t: &str| -> Option<u32> {
1074 let up = t.to_ascii_uppercase();
1075 MONTH_ABBR
1076 .iter()
1077 .position(|a| a.eq_ignore_ascii_case(&up))
1078 .or_else(|| MONTH_FULL.iter().position(|f| f.eq_ignore_ascii_case(&up)))
1079 .map(|i| i as u32 + 1)
1080 };
1081 let mut month: Option<u32> = None;
1082 let mut nums: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
1083 for t in tokens {
1084 if let Some(m) = month_of(t) {
1085 if month.replace(m).is_some() {
1086 return None; }
1088 } else if t.bytes().all(|b| b.is_ascii_digit()) {
1089 nums.push(t);
1090 } else {
1091 return None; }
1093 }
1094 let m = month?;
1095 if nums.len() != 2 {
1096 return None;
1097 }
1098 let (ys, ds) = match (nums[0].len() >= 3, nums[1].len() >= 3) {
1104 (true, true) => return None,
1105 (true, false) => (nums[0], nums[1]),
1106 (false, true) => (nums[1], nums[0]),
1107 (false, false) => {
1108 if order == DateOrder::Ymd {
1109 (nums[0], nums[1])
1110 } else {
1111 (nums[1], nums[0])
1112 }
1113 }
1114 };
1115 let mut y: i32 = ys.parse().ok()?;
1116 if ys.len() <= 2 {
1117 y += if y < 70 { 2000 } else { 1900 };
1118 }
1119 let d: u32 = ds.parse().ok()?;
1120 if !(1..=12).contains(&m) || d < 1 || d > super::days_in_month(y, m) {
1121 return None;
1122 }
1123 Some(days_from_civil(y, m, d))
1124}
1125
1126pub fn parse_timestamp_literal(s: &str) -> Option<i64> {
1131 parse_timestamp_literal_ordered(s, DateOrder::Mdy)
1132}
1133
1134pub fn date_text_is_field_shaped(s: &str) -> bool {
1140 let s = s.trim();
1141 let date_part = match s.find([' ', 'T']) {
1142 Some(i) => &s[..i],
1143 None => s,
1144 };
1145 let b = date_part.as_bytes();
1146 if b.len() == 8 && b.iter().all(u8::is_ascii_digit) {
1147 return true;
1148 }
1149 let fields: alloc::vec::Vec<&str> = date_part.split(['-', '/', '.']).collect();
1150 fields.len() == 3
1151 && fields
1152 .iter()
1153 .all(|f| !f.is_empty() && f.len() <= 4 && f.bytes().all(|c| c.is_ascii_digit()))
1154}
1155
1156pub fn parse_timestamp_literal_ordered(s: &str, order: DateOrder) -> Option<i64> {
1159 parse_timestamp_literal_tz_ordered(s, order).map(|(us, _)| us)
1160}
1161
1162pub fn parse_timestamp_literal_tz_ordered(s: &str, order: DateOrder) -> Option<(i64, bool)> {
1168 if let Some(v) = timestamp_sentinel(s) {
1169 return Some((v, true));
1170 }
1171 let (days, day_micros, tz) = parse_timestamp_parts(s, order)?;
1172 let t = i64::from(days)
1173 .checked_mul(86_400_000_000)?
1174 .checked_add(day_micros)?
1175 .checked_sub(tz.unwrap_or(0))?;
1176 Some((t, tz.is_some()))
1177}
1178
1179fn parse_timestamp_parts(s: &str, order: DateOrder) -> Option<(i32, i64, Option<i64>)> {
1185 let trimmed = s.trim();
1186 if trimmed.eq_ignore_ascii_case("epoch") {
1189 return Some((0, 0, Some(0)));
1190 }
1191 if trimmed.eq_ignore_ascii_case("infinity")
1195 || trimmed.eq_ignore_ascii_case("+infinity")
1196 || trimmed.eq_ignore_ascii_case("-infinity")
1197 {
1198 return None;
1199 }
1200 let (trimmed, era_bc) = match trimmed
1203 .strip_suffix(" BC")
1204 .or_else(|| trimmed.strip_suffix(" bc"))
1205 {
1206 Some(b) => (b.trim_end(), true),
1207 None => (
1208 trimmed
1209 .strip_suffix(" AD")
1210 .or_else(|| trimmed.strip_suffix(" ad"))
1211 .map_or(trimmed, str::trim_end),
1212 false,
1213 ),
1214 };
1215 let (date_part, time_part) = match trimmed.find([' ', 'T']) {
1216 Some(i) => (&trimmed[..i], Some(&trimmed[i + 1..])),
1217 None => (trimmed, None),
1218 };
1219 if time_part.is_none() && parse_date_literal_ordered(date_part, order).is_none() {
1227 if let Some(rest) = date_part.strip_suffix(['Z', 'z']) {
1228 if let Some(d) = parse_date_literal_ordered(rest, order) {
1229 return Some((d, 0, Some(0)));
1230 }
1231 }
1232 for (i, c) in date_part.char_indices().rev() {
1238 if c != '+' {
1239 continue;
1240 }
1241 let (head, tail) = date_part.split_at(i);
1242 let (Some(d), Some(off)) = (
1243 parse_date_literal_ordered(head, order),
1244 parse_tz_offset_suffix(tail, c == '+'),
1245 ) else {
1246 continue;
1247 };
1248 return Some((d, 0, Some(off)));
1249 }
1250 }
1251 let mut days = parse_date_literal_ordered(date_part, order)?;
1252 if era_bc {
1253 let (y, m, d) = civil_from_days(days);
1254 if y < 1 {
1255 return None;
1256 }
1257 days = days_from_civil(1 - y, m, d);
1258 }
1259 let (day_micros, tz_offset) = match time_part {
1260 None => (0, None),
1261 Some(t) => parse_time_of_day_micros_tz(t)?,
1262 };
1263 Some((days, day_micros, tz_offset))
1264}
1265
1266pub fn parse_timestamp_literal_wall_ordered(s: &str, order: DateOrder) -> Option<i64> {
1285 if let Some(v) = timestamp_sentinel(s) {
1286 return Some(v);
1287 }
1288 let (days, day_micros, _tz) = parse_timestamp_parts(s, order)?;
1291 i64::from(days)
1292 .checked_mul(86_400_000_000)?
1293 .checked_add(day_micros)
1294}
1295
1296fn timestamp_sentinel(s: &str) -> Option<i64> {
1299 let t = s.trim();
1300 if t.eq_ignore_ascii_case("epoch") {
1301 return Some(0);
1302 }
1303 if t.eq_ignore_ascii_case("infinity") || t.eq_ignore_ascii_case("+infinity") {
1304 return Some(i64::MAX);
1305 }
1306 if t.eq_ignore_ascii_case("-infinity") {
1307 return Some(i64::MIN);
1308 }
1309 None
1310}
1311
1312#[must_use]
1339pub(crate) fn datetime_input_error_text(text: &str, type_name: &str) -> alloc::string::String {
1340 let (kind, hint) = classify_datetime_input(text);
1341 match kind {
1342 DatetimeInputProblem::Syntax => {
1343 alloc::format!("invalid input syntax for type {type_name}: \"{text}\"")
1344 }
1345 DatetimeInputProblem::OutOfRange => {
1346 let mut m = alloc::format!("date/time field value out of range: \"{text}\"");
1347 if hint {
1348 m.push_str("\nHINT: Perhaps you need a different \"DateStyle\" setting.");
1349 }
1350 m
1351 }
1352 }
1353}
1354
1355enum DatetimeInputProblem {
1356 Syntax,
1357 OutOfRange,
1358}
1359
1360fn classify_datetime_input(text: &str) -> (DatetimeInputProblem, bool) {
1362 let t = text.trim();
1363 if t.is_empty()
1366 || !t
1367 .chars()
1368 .all(|c| c.is_ascii_digit() || matches!(c, '-' | ':' | '.' | ' ' | 'T' | '+' | 'Z'))
1369 {
1370 return (DatetimeInputProblem::Syntax, false);
1371 }
1372 let date_part = t.split([' ', 'T']).next().unwrap_or("");
1374 let fields: alloc::vec::Vec<&str> = date_part.split('-').collect();
1375 if fields.len() != 3
1376 || fields
1377 .iter()
1378 .any(|f| f.is_empty() || !f.chars().all(|c| c.is_ascii_digit()))
1379 {
1380 return (DatetimeInputProblem::Syntax, false);
1381 }
1382 let month = fields[1].parse::<u32>().unwrap_or(0);
1385 let day = fields[2].parse::<u32>().unwrap_or(0);
1386 let field_out_of_range = !(1..=12).contains(&month) || !(1..=31).contains(&day);
1387 (DatetimeInputProblem::OutOfRange, field_out_of_range)
1388}
1389
1390fn parse_time_of_day_micros(t: &str) -> Option<(i64, i64)> {
1392 parse_time_of_day_micros_tz(t).map(|(us, tz)| (us, tz.unwrap_or(0)))
1393}
1394
1395fn parse_time_of_day_micros_tz(t: &str) -> Option<(i64, Option<i64>)> {
1400 let t = t.trim();
1401 let (core, tz_micros) = if let Some(rest) = t.strip_suffix('Z') {
1407 (rest, Some(0i64))
1408 } else if let Some(rest) = t.strip_suffix(" UTC").or_else(|| t.strip_suffix("UTC")) {
1409 (rest, Some(0i64))
1410 } else if let Some((idx, sign_byte)) = find_offset_sign(t) {
1411 let suffix = &t[idx..];
1412 let micros = parse_tz_offset_suffix(suffix, sign_byte == b'+')?;
1413 (&t[..idx], Some(micros))
1414 } else {
1415 (t, None)
1416 };
1417 let (time, frac_str) = match core.split_once('.') {
1418 Some((a, b)) => (a, Some(b)),
1419 None => (core, None),
1420 };
1421 let bytes = time.as_bytes();
1422 let (hh, mm, ss): (i64, i64, i64) = if bytes.len() == 8 && bytes[2] == b':' && bytes[5] == b':'
1426 {
1427 (
1428 time[0..2].parse().ok()?,
1429 time[3..5].parse().ok()?,
1430 time[6..8].parse().ok()?,
1431 )
1432 } else if bytes.len() == 5 && bytes[2] == b':' {
1433 (time[0..2].parse().ok()?, time[3..5].parse().ok()?, 0)
1434 } else {
1435 return None;
1436 };
1437 if !(0..24).contains(&hh) || !(0..60).contains(&mm) || !(0..60).contains(&ss) {
1438 return None;
1439 }
1440 let frac_micros: i64 = match frac_str {
1441 None => 0,
1442 Some(f) => {
1443 if f.is_empty() || f.len() > 9 {
1445 return None;
1446 }
1447 let mut padded = String::with_capacity(6);
1448 padded.push_str(&f[..f.len().min(6)]);
1449 while padded.len() < 6 {
1450 padded.push('0');
1451 }
1452 padded.parse().ok()?
1453 }
1454 };
1455 Some((
1456 ((hh * 3600 + mm * 60 + ss) * 1_000_000) + frac_micros,
1457 tz_micros,
1458 ))
1459}
1460
1461fn find_offset_sign(t: &str) -> Option<(usize, u8)> {
1467 let bytes = t.as_bytes();
1468 if bytes.len() < 6 {
1472 return None;
1473 }
1474 for i in 5..bytes.len() {
1475 match bytes[i] {
1476 b'+' | b'-' => return Some((i, bytes[i])),
1477 _ => {}
1478 }
1479 }
1480 None
1481}
1482
1483fn parse_tz_offset_suffix(suffix: &str, is_positive: bool) -> Option<i64> {
1487 let body = &suffix[1..];
1489 let (hh, mm): (i64, i64) = if let Some((h, m)) = body.split_once(':') {
1490 (h.parse().ok()?, m.parse().ok()?)
1491 } else {
1492 match body.len() {
1493 2 => (body.parse().ok()?, 0),
1494 3 => {
1495 return None;
1499 }
1500 4 => {
1501 let h: i64 = body[0..2].parse().ok()?;
1502 let m: i64 = body[2..4].parse().ok()?;
1503 (h, m)
1504 }
1505 _ => return None,
1506 }
1507 };
1508 if !(0..=18).contains(&hh) || !(0..60).contains(&mm) {
1509 return None;
1510 }
1511 let abs = (hh * 3600 + mm * 60) * 1_000_000;
1512 Some(if is_positive { abs } else { -abs })
1513}
1514
1515pub fn format_interval(months: i32, days: i32, micros: i64) -> String {
1523 let mut parts: Vec<String> = Vec::new();
1524 let years = months / 12;
1525 let mons = months % 12;
1526 let unit = |n: i64, singular: &'static str, plural: &'static str| -> &'static str {
1529 if n == 1 { singular } else { plural }
1530 };
1531 let mut prev_negative = false;
1534 if years != 0 {
1535 parts.push(format!(
1536 "{years} {}",
1537 unit(i64::from(years), "year", "years")
1538 ));
1539 prev_negative = years < 0;
1540 }
1541 if mons != 0 {
1542 let plus = if prev_negative && mons > 0 { "+" } else { "" };
1543 parts.push(format!(
1544 "{plus}{mons} {}",
1545 unit(i64::from(mons), "mon", "mons")
1546 ));
1547 prev_negative = mons < 0;
1548 }
1549 if days != 0 {
1550 let plus = if prev_negative && days > 0 { "+" } else { "" };
1551 parts.push(format!(
1552 "{plus}{days} {}",
1553 unit(i64::from(days), "day", "days")
1554 ));
1555 }
1556 let mut rem = micros;
1557 if rem != 0 {
1558 let neg = rem < 0;
1559 if neg {
1560 rem = -rem;
1561 }
1562 let secs = rem / 1_000_000;
1563 let frac = rem % 1_000_000;
1564 let hh = secs / 3600;
1565 let mm = (secs / 60) % 60;
1566 let ss = secs % 60;
1567 let is_before = if days != 0 {
1572 days < 0
1573 } else if mons != 0 {
1574 mons < 0
1575 } else {
1576 years < 0
1577 };
1578 let sign = if neg {
1579 "-"
1580 } else if is_before {
1581 "+"
1582 } else {
1583 ""
1584 };
1585 if frac == 0 {
1586 parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}"));
1587 } else {
1588 let raw = format!("{frac:06}");
1589 let trimmed = raw.trim_end_matches('0');
1590 parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}.{trimmed}"));
1591 }
1592 }
1593 if parts.is_empty() {
1594 "00:00:00".into()
1596 } else {
1597 parts.join(" ")
1598 }
1599}
1600
1601pub fn format_text_array(items: &[Option<String>]) -> String {
1607 let mut out = String::with_capacity(2 + items.len() * 8);
1608 out.push('{');
1609 for (i, item) in items.iter().enumerate() {
1610 if i > 0 {
1611 out.push(',');
1612 }
1613 match item {
1614 None => out.push_str("NULL"),
1615 Some(s) => {
1616 let needs_quote = s.is_empty()
1621 || s.eq_ignore_ascii_case("NULL")
1622 || s.chars().any(|c| {
1623 matches!(
1624 c,
1625 ',' | '{'
1626 | '}'
1627 | '"'
1628 | '\\'
1629 | ' '
1630 | '\t'
1631 | '\n'
1632 | '\r'
1633 | '\x0b'
1634 | '\x0c'
1635 )
1636 });
1637 if needs_quote {
1638 out.push('"');
1639 for c in s.chars() {
1640 if c == '"' || c == '\\' {
1641 out.push('\\');
1642 }
1643 out.push(c);
1644 }
1645 out.push('"');
1646 } else {
1647 out.push_str(s);
1648 }
1649 }
1650 }
1651 }
1652 out.push('}');
1653 out
1654}
1655
1656pub fn format_int_array(items: &[Option<i32>]) -> String {
1660 let mut out = String::with_capacity(2 + items.len() * 4);
1661 out.push('{');
1662 for (i, item) in items.iter().enumerate() {
1663 if i > 0 {
1664 out.push(',');
1665 }
1666 match item {
1667 None => out.push_str("NULL"),
1668 Some(n) => out.push_str(&n.to_string()),
1669 }
1670 }
1671 out.push('}');
1672 out
1673}
1674
1675pub fn format_bigint_array(items: &[Option<i64>]) -> String {
1678 let mut out = String::with_capacity(2 + items.len() * 6);
1679 out.push('{');
1680 for (i, item) in items.iter().enumerate() {
1681 if i > 0 {
1682 out.push(',');
1683 }
1684 match item {
1685 None => out.push_str("NULL"),
1686 Some(n) => out.push_str(&n.to_string()),
1687 }
1688 }
1689 out.push('}');
1690 out
1691}
1692
1693pub fn format_bool_array(items: &[Option<bool>]) -> String {
1697 let mut out = String::with_capacity(2 + items.len() * 2);
1698 out.push('{');
1699 for (i, item) in items.iter().enumerate() {
1700 if i > 0 {
1701 out.push(',');
1702 }
1703 match item {
1704 None => out.push_str("NULL"),
1705 Some(b) => out.push(if *b { 't' } else { 'f' }),
1706 }
1707 }
1708 out.push('}');
1709 out
1710}
1711
1712pub fn format_smallint_array(items: &[Option<i16>]) -> String {
1714 let mut out = String::with_capacity(2 + items.len() * 4);
1715 out.push('{');
1716 for (i, item) in items.iter().enumerate() {
1717 if i > 0 {
1718 out.push(',');
1719 }
1720 match item {
1721 None => out.push_str("NULL"),
1722 Some(n) => out.push_str(&n.to_string()),
1723 }
1724 }
1725 out.push('}');
1726 out
1727}
1728
1729pub fn format_float_array(items: &[Option<f64>]) -> String {
1733 let mut out = String::with_capacity(2 + items.len() * 8);
1734 out.push('{');
1735 for (i, item) in items.iter().enumerate() {
1736 if i > 0 {
1737 out.push(',');
1738 }
1739 match item {
1740 None => out.push_str("NULL"),
1741 Some(x) => out.push_str(&format_float(*x)),
1744 }
1745 }
1746 out.push('}');
1747 out
1748}
1749
1750pub fn format_numeric_array(items: &[Option<(i128, u16)>]) -> String {
1752 let mut out = String::with_capacity(2 + items.len() * 6);
1753 out.push('{');
1754 for (i, item) in items.iter().enumerate() {
1755 if i > 0 {
1756 out.push(',');
1757 }
1758 match item {
1759 None => out.push_str("NULL"),
1760 Some((scaled, scale)) => out.push_str(&format_numeric(*scaled, *scale)),
1761 }
1762 }
1763 out.push('}');
1764 out
1765}
1766
1767pub fn format_date_array(items: &[Option<i32>]) -> String {
1770 let mut out = String::with_capacity(2 + items.len() * 12);
1771 out.push('{');
1772 for (i, item) in items.iter().enumerate() {
1773 if i > 0 {
1774 out.push(',');
1775 }
1776 match item {
1777 None => out.push_str("NULL"),
1778 Some(d) => out.push_str(&format_date(*d)),
1779 }
1780 }
1781 out.push('}');
1782 out
1783}
1784
1785pub fn format_timestamp_array(items: &[Option<i64>], with_tz: bool) -> String {
1791 let mut out = String::with_capacity(2 + items.len() * 22);
1792 out.push('{');
1793 for (i, item) in items.iter().enumerate() {
1794 if i > 0 {
1795 out.push(',');
1796 }
1797 match item {
1798 None => out.push_str("NULL"),
1799 Some(t) => {
1800 out.push('"');
1801 if with_tz {
1802 out.push_str(&format_timestamptz(*t));
1803 } else {
1804 out.push_str(&format_timestamp(*t));
1805 }
1806 out.push('"');
1807 }
1808 }
1809 }
1810 out.push('}');
1811 out
1812}
1813
1814pub fn format_uuid_array(items: &[Option<[u8; 16]>]) -> String {
1818 let mut out = String::with_capacity(2 + items.len() * 38);
1819 out.push('{');
1820 for (i, item) in items.iter().enumerate() {
1821 if i > 0 {
1822 out.push(',');
1823 }
1824 match item {
1825 None => out.push_str("NULL"),
1826 Some(b) => out.push_str(&spg_storage::format_uuid(b)),
1827 }
1828 }
1829 out.push('}');
1830 out
1831}
1832
1833pub fn format_bytea_array(items: &[Option<Vec<u8>>]) -> String {
1838 let mut out = String::with_capacity(2 + items.len() * 8);
1839 out.push('{');
1840 for (i, item) in items.iter().enumerate() {
1841 if i > 0 {
1842 out.push(',');
1843 }
1844 match item {
1845 None => out.push_str("NULL"),
1846 Some(b) => {
1847 out.push('"');
1848 let hex = format_bytea_hex(b);
1849 for c in hex.chars() {
1852 if c == '\\' {
1853 out.push('\\');
1854 }
1855 out.push(c);
1856 }
1857 out.push('"');
1858 }
1859 }
1860 }
1861 out.push('}');
1862 out
1863}
1864
1865pub fn format_interval_array(items: &[Option<spg_storage::IntervalSpan>]) -> String {
1872 let mut out = String::with_capacity(2 + items.len() * 12);
1873 out.push('{');
1874 for (i, item) in items.iter().enumerate() {
1875 if i > 0 {
1876 out.push(',');
1877 }
1878 match item {
1879 None => out.push_str("NULL"),
1880 Some(span) => {
1881 if span.kind.is_finite() {
1885 out.push('"');
1886 out.push_str(&format_interval(span.months, span.days, span.micros));
1887 out.push('"');
1888 } else {
1889 out.push_str(&format_interval_kinded(0, 0, 0, span.kind));
1890 }
1891 }
1892 }
1893 }
1894 out.push('}');
1895 out
1896}
1897
1898#[must_use]
1904pub fn format_bytea_escape(b: &[u8]) -> String {
1905 let mut out = String::with_capacity(b.len());
1906 for &byte in b {
1907 match byte {
1908 b'\\' => out.push_str("\\\\"),
1909 0x20..=0x7e => out.push(byte as char),
1910 _ => out.push_str(&alloc::format!("\\{byte:03o}")),
1911 }
1912 }
1913 out
1914}
1915
1916pub fn format_bytea_hex(b: &[u8]) -> String {
1917 let mut out = String::with_capacity(2 + 2 * b.len());
1918 out.push_str("\\x");
1919 const HEX: &[u8; 16] = b"0123456789abcdef";
1920 for byte in b {
1921 out.push(HEX[(byte >> 4) as usize] as char);
1922 out.push(HEX[(byte & 0x0F) as usize] as char);
1923 }
1924 out
1925}
1926
1927pub fn format_numeric_kind(kind: spg_storage::NumericKind, scaled: i128, scale: u16) -> String {
1934 use spg_storage::NumericKind;
1935 match kind {
1936 NumericKind::Finite => format_numeric(scaled, scale),
1937 NumericKind::NaN => String::from("NaN"),
1938 NumericKind::PosInf => String::from("Infinity"),
1939 NumericKind::NegInf => String::from("-Infinity"),
1940 }
1941}
1942
1943pub fn format_numeric(scaled: i128, scale: u16) -> String {
1944 if scale == 0 {
1945 return format!("{scaled}");
1946 }
1947 let negative = scaled < 0;
1948 let mag_str = scaled.unsigned_abs().to_string();
1949 let mag_bytes = mag_str.as_bytes();
1950 let scale_u = scale as usize;
1951 let mut out = String::with_capacity(mag_str.len() + 3);
1952 if negative {
1953 out.push('-');
1954 }
1955 if mag_bytes.len() <= scale_u {
1956 out.push('0');
1957 out.push('.');
1958 for _ in mag_bytes.len()..scale_u {
1959 out.push('0');
1960 }
1961 out.push_str(&mag_str);
1962 } else {
1963 let split = mag_bytes.len() - scale_u;
1964 out.push_str(&mag_str[..split]);
1965 out.push('.');
1966 out.push_str(&mag_str[split..]);
1967 }
1968 out
1969}
1970
1971fn shortest_float_sci(x: f64) -> String {
1989 let (m, e) = f64_mantissa_exp(x);
1990 let (hi_m, hi_e) = (2 * m + 1, e - 1);
1993 let (lo_m, lo_e) = if m == 1 << 52 && e > f64_min_exp() {
1994 (4 * m - 1, e - 2)
1995 } else {
1996 (2 * m - 1, e - 1)
1997 };
1998 for p in 1..=17u32 {
1999 let cand = alloc::format!("{x:.*e}", (p - 1) as usize);
2000 let Ok(v) = cand.parse::<f64>() else { continue };
2001 if v != x {
2002 continue;
2003 }
2004 let Some((d, k)) = sci_to_digits_exp(&cand) else {
2005 continue;
2006 };
2007 if !decimal_eq_binary(d, k, hi_m, hi_e) && !decimal_eq_binary(d, k, lo_m, lo_e) {
2008 return cand;
2009 }
2010 }
2011 alloc::format!("{x:e}")
2012}
2013
2014fn f64_mantissa_exp(x: f64) -> (u128, i32) {
2017 let bits = x.abs().to_bits();
2018 let biased = ((bits >> 52) & 0x7ff) as i32;
2019 let frac = u128::from(bits & 0x000f_ffff_ffff_ffff);
2020 if biased == 0 {
2021 (frac, -1074) } else {
2023 ((1u128 << 52) | frac, biased - 1075)
2024 }
2025}
2026
2027const fn f64_min_exp() -> i32 {
2030 -1074
2031}
2032
2033fn sci_to_digits_exp(sci: &str) -> Option<(u128, i32)> {
2037 let epos = sci.find('e')?;
2038 let (mant, rest) = sci.split_at(epos);
2039 let exp: i32 = rest[1..].parse().ok()?;
2040 let mant = mant.strip_prefix('-').unwrap_or(mant);
2041 let (int_part, frac_part) = match mant.split_once('.') {
2042 Some((a, b)) => (a, b),
2043 None => (mant, ""),
2044 };
2045 let mut digits: u128 = 0;
2046 for c in int_part.chars().chain(frac_part.chars()) {
2047 digits = digits
2048 .checked_mul(10)?
2049 .checked_add(u128::from(c as u8 - b'0'))?;
2050 }
2051 Some((digits, exp - i32::try_from(frac_part.len()).ok()?))
2052}
2053
2054fn decimal_eq_binary(d: u128, k: i32, m: u128, e: i32) -> bool {
2060 if d == 0 {
2061 return false;
2062 }
2063 let a = i32::try_from(d.trailing_zeros()).unwrap_or(i32::MAX);
2064 let d_odd = d >> d.trailing_zeros();
2065 if k >= 0 {
2066 let mut lhs = d_odd;
2068 for _ in 0..k {
2069 match lhs.checked_mul(5) {
2070 Some(v) if v <= m => lhs = v,
2071 _ => return false,
2072 }
2073 }
2074 lhs == m && a + k == e
2075 } else {
2076 let j = -k;
2078 let mut lhs = d_odd;
2079 for _ in 0..j {
2080 if lhs % 5 != 0 {
2081 return false;
2082 }
2083 lhs /= 5;
2084 }
2085 lhs == m && a - j == e
2086 }
2087}