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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::any::Any;
use std::fmt::Write;
use std::sync::Arc;
use core::num::FpCategory;
use arrow::{
array::{Array, ArrayRef, LargeStringArray, StringArray, StringViewArray},
datatypes::{DataType, Field, FieldRef},
};
use bigdecimal::{
BigDecimal, ToPrimitive,
num_bigint::{BigInt, Sign},
};
use chrono::{DateTime, Datelike, Timelike, Utc};
use datafusion_common::{
DataFusionError, Result, ScalarValue, exec_datafusion_err, exec_err, plan_err,
};
use datafusion_expr::{
ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature,
TypeSignature, Volatility,
};
/// Spark-compatible `format_string` expression
/// <https://spark.apache.org/docs/latest/api/sql/index.html#format_string>
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct FormatStringFunc {
signature: Signature,
aliases: Vec<String>,
}
impl Default for FormatStringFunc {
fn default() -> Self {
Self::new()
}
}
impl FormatStringFunc {
pub fn new() -> Self {
Self {
signature: Signature::new(TypeSignature::VariadicAny, Volatility::Immutable),
aliases: vec![String::from("printf")],
}
}
}
impl ScalarUDFImpl for FormatStringFunc {
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &str {
"format_string"
}
fn aliases(&self) -> &[String] {
&self.aliases
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
datafusion_common::internal_err!(
"return_type should not be called, use return_field_from_args instead"
)
}
fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
match args.arg_fields[0].data_type() {
DataType::Null => {
Ok(Arc::new(Field::new("format_string", DataType::Utf8, true)))
}
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => {
Ok(Arc::clone(&args.arg_fields[0]))
}
_ => exec_err!(
"format_string expects the first argument to be Utf8, LargeUtf8 or Utf8View, got {} instead",
args.arg_fields[0].data_type()
),
}
}
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
let len = args.args.iter().find_map(|arg| match arg {
ColumnarValue::Scalar(_) => None,
ColumnarValue::Array(a) => Some(a.len()),
});
let is_scalar = len.is_none();
let data_types = args.args[1..]
.iter()
.map(|arg| arg.data_type())
.collect::<Vec<_>>();
let fmt_type = args.args[0].data_type();
match &args.args[0] {
ColumnarValue::Scalar(ScalarValue::Null) => {
Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)))
}
ColumnarValue::Scalar(ScalarValue::Utf8(None)) => {
Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)))
}
ColumnarValue::Scalar(ScalarValue::LargeUtf8(None)) => {
Ok(ColumnarValue::Scalar(ScalarValue::LargeUtf8(None)))
}
ColumnarValue::Scalar(ScalarValue::Utf8View(None)) => {
Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(None)))
}
ColumnarValue::Scalar(ScalarValue::Utf8(Some(fmt)))
| ColumnarValue::Scalar(ScalarValue::LargeUtf8(Some(fmt)))
| ColumnarValue::Scalar(ScalarValue::Utf8View(Some(fmt))) => {
let formatter = Formatter::parse(fmt, &data_types)?;
let mut result = Vec::with_capacity(len.unwrap_or(1));
for i in 0..len.unwrap_or(1) {
let scalars = args.args[1..]
.iter()
.map(|arg| try_to_scalar(arg.clone(), i))
.collect::<Result<Vec<_>>>()?;
let formatted = formatter.format(&scalars)?;
result.push(formatted);
}
if is_scalar {
let scalar_result = result.pop().unwrap();
match fmt_type {
DataType::Utf8 => Ok(ColumnarValue::Scalar(ScalarValue::Utf8(
Some(scalar_result),
))),
DataType::LargeUtf8 => Ok(ColumnarValue::Scalar(
ScalarValue::LargeUtf8(Some(scalar_result)),
)),
DataType::Utf8View => Ok(ColumnarValue::Scalar(
ScalarValue::Utf8View(Some(scalar_result)),
)),
_ => unreachable!(),
}
} else {
let array: ArrayRef = match fmt_type {
DataType::Utf8 => Arc::new(StringArray::from(result)),
DataType::LargeUtf8 => Arc::new(LargeStringArray::from(result)),
DataType::Utf8View => Arc::new(StringViewArray::from(result)),
_ => unreachable!(),
};
Ok(ColumnarValue::Array(array))
}
}
ColumnarValue::Array(fmts) => {
let mut result = Vec::with_capacity(len.unwrap());
for i in 0..len.unwrap() {
let fmt = ScalarValue::try_from_array(fmts, i)?;
match fmt.try_as_str() {
Some(Some(fmt)) => {
let formatter = Formatter::parse(fmt, &data_types)?;
let scalars = args.args[1..]
.iter()
.map(|arg| try_to_scalar(arg.clone(), i))
.collect::<Result<Vec<_>>>()?;
let formatted = formatter.format(&scalars)?;
result.push(Some(formatted));
}
Some(None) => {
result.push(None);
}
_ => unreachable!(),
}
}
let array: ArrayRef = match fmt_type {
DataType::Utf8 => Arc::new(StringArray::from(result)),
DataType::LargeUtf8 => Arc::new(LargeStringArray::from(result)),
DataType::Utf8View => Arc::new(StringViewArray::from(result)),
_ => unreachable!(),
};
Ok(ColumnarValue::Array(array))
}
_ => exec_err!(
"The format_string function expects the first argument to be a string"
),
}
}
}
fn try_to_scalar(arg: ColumnarValue, index: usize) -> Result<ScalarValue> {
match arg {
ColumnarValue::Scalar(scalar) => Ok(scalar),
ColumnarValue::Array(array) => ScalarValue::try_from_array(&array, index),
}
}
/// Compatible with `java.util.Formatter`
#[derive(Debug)]
pub struct Formatter<'a> {
pub elements: Vec<FormatElement<'a>>,
pub arg_num: usize,
}
impl<'a> Formatter<'a> {
pub fn new(elements: Vec<FormatElement<'a>>) -> Self {
let arg_num = elements
.iter()
.map(|element| match element {
FormatElement::Format(spec) => spec.argument_index,
_ => 0,
})
.max()
.unwrap_or(0);
Self { elements, arg_num }
}
/// Parses a printf-style format string into a Formatter with validation.
///
/// This method implements a comprehensive parser for Java `java.util.Formatter` syntax,
/// processing the format string character by character to identify and validate format
/// specifiers against the provided argument types.
///
/// # Arguments
///
/// * `fmt` - The format string containing literal text and format specifiers
/// * `arg_types` - Array of DataFusion DataTypes corresponding to the arguments
///
/// # Parsing Process
///
/// The parser operates in several phases:
///
/// 1. **String Scanning**: Iterates through the format string looking for '%' characters
/// that mark the beginning of format specifiers or special sequences.
///
/// 2. **Special Sequence Handling**: Processes escape sequences:
/// - `%%` becomes a literal '%' character
/// - `%n` becomes a newline character
/// - `%<` indicates reuse of the previous argument with a new format specifier
///
/// 3. **Argument Index Resolution**: Determines which argument each format specifier refers to:
/// - Sequential indexing: arguments are consumed in order (1, 2, 3, ...)
/// - Positional indexing: explicit argument position using `%n$` syntax
/// - Previous argument reuse: `%<` references the last used argument
///
/// 4. **Format Specifier Parsing**: For each format specifier, extracts:
/// - Flags (-, +, space, #, 0, ',', '(')
/// - Width specification (minimum field width)
/// - Precision specification (decimal places or maximum characters)
/// - Conversion type (d, s, f, x, etc.)
///
/// 5. **Type Validation**: Verifies that each format specifier's conversion type
/// is compatible with the corresponding argument's DataType. For example:
/// - Integer conversions (%d, %x, %o) require integer DataTypes
/// - String conversions (%s, %S) accept any DataType
/// - Float conversions (%f, %e, %g) require numeric DataTypes
///
/// 6. **Element Construction**: Creates FormatElement instances for:
/// - Verbatim text sections (copied directly to output)
/// - Validated format specifiers with their parsed parameters
///
/// # Internal State Management
///
/// The parser maintains several state variables:
/// - `argument_index`: Tracks the current sequential argument position
/// - `prev`: Remembers the last used argument index for `%<` references
/// - `res`: Accumulates the parsed FormatElement instances
/// - `rem`: Points to the remaining unparsed portion of the format string
///
/// # Validation and Error Handling
///
/// The parser performs extensive validation including:
/// - Argument index bounds checking against the provided arg_types array
/// - Format specifier syntax validation
/// - Type compatibility verification between conversion types and DataTypes
/// - Detection of malformed numeric parameters and invalid flag combinations
///
/// # Returns
///
/// Returns a Formatter containing the parsed elements and the maximum argument
/// index encountered, enabling efficient argument validation during formatting.
pub fn parse(fmt: &'a str, arg_types: &[DataType]) -> Result<Self> {
// find the first %
let mut res = Vec::new();
let mut rem = fmt;
let mut argument_index = 0;
let mut prev: Option<usize> = None;
while !rem.is_empty() {
if let Some((verbatim_prefix, rest)) = rem.split_once('%') {
if !verbatim_prefix.is_empty() {
res.push(FormatElement::Verbatim(verbatim_prefix));
}
if let Some(rest) = rest.strip_prefix('%') {
res.push(FormatElement::Verbatim("%"));
rem = rest;
continue;
}
if let Some(rest) = rest.strip_prefix('n') {
res.push(FormatElement::Verbatim("\n"));
rem = rest;
continue;
}
if let Some(rest) = rest.strip_prefix('<') {
// %< means reuse the previous argument
let Some(p) = prev else {
return exec_err!("No previous argument to reference");
};
let (spec, rest) =
take_conversion_specifier(rest, p, &arg_types[p - 1])?;
res.push(FormatElement::Format(spec));
rem = rest;
continue;
}
let (current_argument_index, rest2) = take_numeric_param(rest, false);
let (current_argument_index, rest) =
match (current_argument_index, rest2.starts_with('$')) {
(NumericParam::Literal(index), true) => {
(index as usize, &rest2[1..])
}
(NumericParam::FromArgument, true) => {
return exec_err!("Invalid numeric parameter");
}
(_, false) => {
argument_index += 1;
(argument_index, rest)
}
};
if current_argument_index == 0 || current_argument_index > arg_types.len()
{
return exec_err!(
"Argument index {} is out of bounds",
current_argument_index
);
}
let (spec, rest) = take_conversion_specifier(
rest,
current_argument_index,
&arg_types[current_argument_index - 1],
)
.map_err(|e| exec_datafusion_err!("{:?}, format string: {:?}", e, fmt))?;
res.push(FormatElement::Format(spec));
prev = Some(spec.argument_index);
rem = rest;
} else {
res.push(FormatElement::Verbatim(rem));
break;
}
}
Ok(Self::new(res))
}
pub fn format(&self, args: &[ScalarValue]) -> Result<String> {
if args.len() < self.arg_num {
return exec_err!(
"Expected at least {} arguments, got {}",
self.arg_num,
args.len()
);
}
let mut string = String::new();
for element in &self.elements {
match element {
FormatElement::Verbatim(text) => {
string.push_str(text);
}
FormatElement::Format(spec) => {
spec.format(&mut string, &args[spec.argument_index - 1])?;
}
}
}
Ok(string)
}
}
#[derive(Debug)]
pub enum FormatElement<'a> {
/// Some characters that are copied to the output as-is
Verbatim(&'a str),
/// A format specifier
Format(ConversionSpecifier),
}
/// Parsed printf conversion specifier
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConversionSpecifier {
pub argument_index: usize,
/// flag `#`: use `0x`, etc?
pub alt_form: bool,
/// flag `0`: left-pad with zeros?
pub zero_pad: bool,
/// flag `-`: left-adjust (pad with spaces on the right)
pub left_adj: bool,
/// flag `' '` (space): indicate sign with a space?
pub space_sign: bool,
/// flag `+`: Always show sign? (for signed numbers)
pub force_sign: bool,
/// flag `,`: include locale-specific grouping separators
pub grouping_separator: bool,
/// flag `(`: enclose negative numbers in parentheses
pub negative_in_parentheses: bool,
/// field width
pub width: NumericParam,
/// floating point field precision
pub precision: NumericParam,
/// data type
pub conversion_type: ConversionType,
}
/// Width / precision parameter
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericParam {
/// The literal width
Literal(i32),
/// Get the width from the previous argument
FromArgument,
}
/// Printf data type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConversionType {
/// `B`
BooleanUpper,
/// `b`
BooleanLower,
/// Not implemented yet. Can be implemented after <https://github.com/apache/datafusion/pull/17093> is merged
/// `h`
HexHashLower,
/// `H`
HexHashUpper,
/// `d`
DecInt,
/// `o`
OctInt,
/// `x`
HexIntLower,
/// `X`
HexIntUpper,
/// `e`
SciFloatLower,
/// `E`
SciFloatUpper,
/// `f`
DecFloatLower,
/// `g`
CompactFloatLower,
/// `G`
CompactFloatUpper,
/// `a`
HexFloatLower,
/// `A`
HexFloatUpper,
/// `t`
TimeLower(TimeFormat),
/// `T`
TimeUpper(TimeFormat),
/// `c`
CharLower,
/// `C`
CharUpper,
/// `s`
StringLower,
/// `S`
StringUpper,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeFormat {
// Hour of the day for the 24-hour clock,
// formatted as two digits with a leading zero as necessary i.e. 00 - 23. 00 corresponds to midnight.
HUpper,
// Hour for the 12-hour clock,
// formatted as two digits with a leading zero as necessary, i.e. 01 - 12. 01 corresponds to one o'clock (either morning or afternoon).
IUpper,
// Hour of the day for the 24-hour clock,
// i.e. 0 - 23. 0 corresponds to midnight.
KLower,
// Hour for the 12-hour clock,
// i.e. 1 - 12. 1 corresponds to one o'clock (either morning or afternoon).
LLower,
// Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.
MUpper,
// Seconds within the minute, formatted as two digits with a leading zero as necessary,
// i.e. 00 - 60 ("60" is a special value required to support leap seconds).
SUpper,
// Millisecond within the second formatted as three digits with leading zeros as necessary, i.e. 000 - 999.
LUpper,
// Nanosecond within the second, formatted as nine digits with leading zeros as necessary,
// i.e. 000000000 - 999999999. The precision of this value is limited by the resolution of the underlying operating system or hardware.
NUpper,
// Locale-specific morning or afternoon marker in lower case, e.g."am" or "pm".
// Use of the conversion prefix 'T' forces this output to upper case. (Note that 'p' produces lower-case output.
// This is different from GNU date and POSIX strftime(3c) which produce upper-case output.)
PLower,
// RFC 822 style numeric time zone offset from GMT,
// e.g. -0800. This value will be adjusted as necessary for Daylight Saving Time.
// For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
ZLower,
// A string representing the abbreviation for the time zone. This value will be adjusted as necessary for Daylight Saving Time.
// For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
// The Formatter's locale will supersede the locale of the argument (if any).
ZUpper,
// Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC,
// i.e. Long.MIN_VALUE/1000 to Long.MAX_VALUE/1000.
SLower,
// Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC,
// i.e. Long.MIN_VALUE to Long.MAX_VALUE. The precision of this value is limited by the resolution of the underlying operating system or hardware.
QUpper,
// Locale-specific full month name, e.g. "January", "February".
BUpper,
// Locale-specific abbreviated month name, e.g. "Jan", "Feb".
BLower,
// Locale-specific full weekday name, e.g. "Monday", "Tuesday".
AUpper,
// Locale-specific abbreviated weekday name, e.g. "Mon", "Tue".
ALower,
// Four-digit year divided by 100, formatted as two digits with leading zero as necessary, i.e. 00 - 99
CUpper,
// Year, formatted to at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar.
YUpper,
// Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99.
YLower,
// Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366 for the Gregorian calendar. 001 corresponds to the first day of the year.
JLower,
// Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13, where "01" is the first month of the year and ("13" is a special value required to support lunar calendars).
MLower,
// Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31, where "01" is the first day of the month.
DLower,
// Day of month, formatted as two digits, i.e. 1 - 31 where "1" is the first day of the month.
ELower,
// Time formatted for the 24-hour clock as "%tH:%tM"
RUpper,
// Time formatted for the 24-hour clock as "%tH:%tM:%tS"
TUpper,
// Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp". The location of the morning or afternoon marker ('%Tp') may be locale-dependent.
RLower,
// Date formatted as "%tm/%td/%ty"
DUpper,
// ISO 8601 complete date formatted as "%tY-%tm-%td"
FUpper,
// Date and time formatted as "%ta %tb %td %tT %tZ %tY", e.g. "Sun Jul 20 16:17:00 EDT 1969"
CLower,
}
impl TryFrom<char> for TimeFormat {
type Error = DataFusionError;
fn try_from(value: char) -> Result<Self, Self::Error> {
match value {
'H' => Ok(TimeFormat::HUpper),
'I' => Ok(TimeFormat::IUpper),
'k' => Ok(TimeFormat::KLower),
'l' => Ok(TimeFormat::LLower),
'M' => Ok(TimeFormat::MUpper),
'S' => Ok(TimeFormat::SUpper),
'L' => Ok(TimeFormat::LUpper),
'N' => Ok(TimeFormat::NUpper),
'p' => Ok(TimeFormat::PLower),
'z' => Ok(TimeFormat::ZLower),
'Z' => Ok(TimeFormat::ZUpper),
's' => Ok(TimeFormat::SLower),
'Q' => Ok(TimeFormat::QUpper),
'B' => Ok(TimeFormat::BUpper),
'b' | 'h' => Ok(TimeFormat::BLower),
'A' => Ok(TimeFormat::AUpper),
'a' => Ok(TimeFormat::ALower),
'C' => Ok(TimeFormat::CUpper),
'Y' => Ok(TimeFormat::YUpper),
'y' => Ok(TimeFormat::YLower),
'j' => Ok(TimeFormat::JLower),
'm' => Ok(TimeFormat::MLower),
'd' => Ok(TimeFormat::DLower),
'e' => Ok(TimeFormat::ELower),
'R' => Ok(TimeFormat::RUpper),
'T' => Ok(TimeFormat::TUpper),
'r' => Ok(TimeFormat::RLower),
'D' => Ok(TimeFormat::DUpper),
'F' => Ok(TimeFormat::FUpper),
'c' => Ok(TimeFormat::CLower),
_ => exec_err!("Invalid time format: {}", value),
}
}
}
impl ConversionType {
pub fn validate(&self, arg_type: &DataType) -> Result<()> {
match self {
ConversionType::BooleanLower | ConversionType::BooleanUpper => {
if *arg_type != DataType::Boolean {
return exec_err!(
"Invalid argument type for boolean conversion: {:?}",
arg_type
);
}
}
ConversionType::CharLower | ConversionType::CharUpper => {
if !matches!(
arg_type,
DataType::Int8
| DataType::UInt8
| DataType::Int16
| DataType::UInt16
| DataType::Int32
| DataType::UInt32
| DataType::Int64
| DataType::UInt64
) {
return exec_err!(
"Invalid argument type for char conversion: {:?}",
arg_type
);
}
}
ConversionType::DecInt
| ConversionType::OctInt
| ConversionType::HexIntLower
| ConversionType::HexIntUpper => {
if !arg_type.is_integer() {
return exec_err!(
"Invalid argument type for integer conversion: {:?}",
arg_type
);
}
}
ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::DecFloatLower
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper
| ConversionType::HexFloatLower
| ConversionType::HexFloatUpper => {
if !arg_type.is_numeric() {
return exec_err!(
"Invalid argument type for float conversion: {:?}",
arg_type
);
}
}
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_) => {
if !arg_type.is_temporal() {
return exec_err!(
"Invalid argument type for time conversion: {:?}",
arg_type
);
}
}
_ => {}
}
Ok(())
}
fn supports_integer(&self) -> bool {
matches!(
self,
ConversionType::DecInt
| ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt
| ConversionType::CharLower
| ConversionType::CharUpper
| ConversionType::StringLower
| ConversionType::StringUpper
)
}
fn supports_float(&self) -> bool {
matches!(
self,
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper
| ConversionType::StringLower
| ConversionType::StringUpper
| ConversionType::HexFloatLower
| ConversionType::HexFloatUpper
)
}
fn supports_decimal(&self) -> bool {
matches!(
self,
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper
| ConversionType::StringLower
| ConversionType::StringUpper
)
}
fn supports_time(&self) -> bool {
matches!(
self,
ConversionType::TimeLower(_)
| ConversionType::TimeUpper(_)
| ConversionType::StringLower
| ConversionType::StringUpper
)
}
fn is_upper(&self) -> bool {
matches!(
self,
ConversionType::BooleanUpper
| ConversionType::HexHashUpper
| ConversionType::HexIntUpper
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatUpper
| ConversionType::HexFloatUpper
| ConversionType::TimeUpper(_)
| ConversionType::CharUpper
| ConversionType::StringUpper
)
}
}
fn take_conversion_specifier<'a>(
mut s: &'a str,
argument_index: usize,
arg_type: &DataType,
) -> Result<(ConversionSpecifier, &'a str)> {
let mut spec = ConversionSpecifier {
argument_index,
alt_form: false,
zero_pad: false,
left_adj: false,
space_sign: false,
force_sign: false,
grouping_separator: false,
negative_in_parentheses: false,
width: NumericParam::Literal(0),
precision: NumericParam::FromArgument, // Placeholder - must not be returned!
// ignore length modifier
conversion_type: ConversionType::DecInt,
};
// parse flags
loop {
match s.chars().next() {
Some('#') => {
spec.alt_form = true;
}
Some('0') => {
if spec.left_adj {
return exec_err!("Invalid flag combination: '0' and '-'");
}
spec.zero_pad = true;
}
Some('-') => {
spec.left_adj = true;
}
Some(' ') => {
if spec.force_sign {
return exec_err!("Invalid flag combination: '+' and ' '");
}
spec.space_sign = true;
}
Some('+') => {
if spec.space_sign {
return exec_err!("Invalid flag combination: '+' and ' '");
}
spec.force_sign = true;
}
Some(',') => {
spec.grouping_separator = true;
}
Some('(') => {
spec.negative_in_parentheses = true;
}
_ => {
break;
}
}
s = &s[1..];
}
// parse width
let (w, mut s) = take_numeric_param(s, false);
spec.width = w;
// parse precision
if matches!(s.chars().next(), Some('.')) {
s = &s[1..];
let (p, s2) = take_numeric_param(s, true);
spec.precision = p;
s = s2;
}
let mut chars = s.chars();
let mut offset = 1;
// parse conversion type
spec.conversion_type = match chars.next() {
Some('b') => ConversionType::BooleanLower,
Some('B') => ConversionType::BooleanUpper,
Some('h') => ConversionType::HexHashLower,
Some('H') => ConversionType::HexHashUpper,
Some('s') => ConversionType::StringLower,
Some('S') => ConversionType::StringUpper,
Some('c') => ConversionType::CharLower,
Some('C') => ConversionType::CharUpper,
Some('d') => ConversionType::DecInt,
Some('o') => ConversionType::OctInt,
Some('x') => ConversionType::HexIntLower,
Some('X') => ConversionType::HexIntUpper,
Some('e') => ConversionType::SciFloatLower,
Some('E') => ConversionType::SciFloatUpper,
Some('f') => ConversionType::DecFloatLower,
Some('g') => ConversionType::CompactFloatLower,
Some('G') => ConversionType::CompactFloatUpper,
Some('a') => ConversionType::HexFloatLower,
Some('A') => ConversionType::HexFloatUpper,
Some('t') => {
let Some(chr) = chars.next() else {
return exec_err!("Invalid time format: {}", s);
};
offset += 1;
ConversionType::TimeLower(chr.try_into()?)
}
Some('T') => {
let Some(chr) = chars.next() else {
return exec_err!("Invalid time format: {}", s);
};
offset += 1;
ConversionType::TimeUpper(chr.try_into()?)
}
chr => {
return plan_err!("Invalid conversion type: {:?}", chr);
}
};
spec.conversion_type.validate(arg_type)?;
Ok((spec, &s[offset..]))
}
fn take_numeric_param(s: &str, zero: bool) -> (NumericParam, &str) {
match s.chars().next() {
Some(digit) if (if zero { '0'..='9' } else { '1'..='9' }).contains(&digit) => {
let mut s = s;
let mut w = 0;
loop {
match s.chars().next() {
Some(digit) if digit.is_ascii_digit() => {
w = 10 * w + (digit as i32 - '0' as i32);
}
_ => {
break;
}
}
s = &s[1..];
}
(NumericParam::Literal(w), s)
}
_ => (NumericParam::FromArgument, s),
}
}
impl ConversionSpecifier {
pub fn format(&self, string: &mut String, value: &ScalarValue) -> Result<()> {
match value {
ScalarValue::Boolean(value) => match self.conversion_type {
ConversionType::StringLower | ConversionType::StringUpper => {
self.format_string(string, &value.unwrap_or(false).to_string())
}
_ => self.format_boolean(string, value),
},
ScalarValue::Int8(value) => match (self.conversion_type, value) {
(ConversionType::DecInt, Some(value)) => {
self.format_signed(string, *value as i64)
}
(
ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, (*value as u8) as u64),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(string, *value as u8 as char)
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Int8",
self.conversion_type
)
}
},
ScalarValue::Int16(value) => match (self.conversion_type, value) {
(ConversionType::DecInt, Some(value)) => {
self.format_signed(string, *value as i64)
}
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(
string,
char::from_u32((*value as u16) as u32).unwrap(),
)
}
(
ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, (*value as u16) as u64),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Int16",
self.conversion_type
)
}
},
ScalarValue::Int32(value) => match (self.conversion_type, value) {
(ConversionType::DecInt, Some(value)) => {
self.format_signed(string, *value as i64)
}
(
ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, (*value as u32) as u64),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(string, char::from_u32(*value as u32).unwrap())
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Int32",
self.conversion_type
)
}
},
ScalarValue::Int64(value) => match (self.conversion_type, value) {
(ConversionType::DecInt, Some(value)) => {
self.format_signed(string, *value)
}
(
ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, *value as u64),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(
string,
char::from_u32((*value as u64) as u32).unwrap(),
)
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Int64",
self.conversion_type
)
}
},
ScalarValue::UInt8(value) => match (self.conversion_type, value) {
(
ConversionType::DecInt
| ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, *value as u64),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(string, *value as char)
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for UInt8",
self.conversion_type
)
}
},
ScalarValue::UInt16(value) => match (self.conversion_type, value) {
(
ConversionType::DecInt
| ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, *value as u64),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(string, char::from_u32(*value as u32).unwrap())
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for UInt16",
self.conversion_type
)
}
},
ScalarValue::UInt32(value) => match (self.conversion_type, value) {
(
ConversionType::DecInt
| ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, *value as u64),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(string, char::from_u32(*value).unwrap())
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for UInt32",
self.conversion_type
)
}
},
ScalarValue::UInt64(value) => match (self.conversion_type, value) {
(
ConversionType::DecInt
| ConversionType::HexIntLower
| ConversionType::HexIntUpper
| ConversionType::OctInt,
Some(value),
) => self.format_unsigned(string, *value),
(ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
self.format_char(string, char::from_u32(*value as u32).unwrap())
}
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_integer() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for UInt64",
self.conversion_type
)
}
},
ScalarValue::Float16(value) => match (self.conversion_type, value) {
(
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper,
Some(value),
) => self.format_float(string, value.to_f64().unwrap()),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_f32().unwrap().spark_string()),
(
ConversionType::HexFloatLower | ConversionType::HexFloatUpper,
Some(value),
) => self.format_hex_float(string, value.to_f64().unwrap()),
(t, None) if t.supports_float() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Float16",
self.conversion_type
)
}
},
ScalarValue::Float32(value) => match (self.conversion_type, value) {
(
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper,
Some(value),
) => self.format_float(string, *value as f64),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.spark_string()),
(
ConversionType::HexFloatLower | ConversionType::HexFloatUpper,
Some(value),
) => self.format_hex_float(string, *value as f64),
(t, None) if t.supports_float() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Float32",
self.conversion_type
)
}
},
ScalarValue::Float64(value) => match (self.conversion_type, value) {
(
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper,
Some(value),
) => self.format_float(string, *value),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.spark_string()),
(
ConversionType::HexFloatLower | ConversionType::HexFloatUpper,
Some(value),
) => self.format_hex_float(string, *value),
(t, None) if t.supports_float() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Float64",
self.conversion_type
)
}
},
ScalarValue::Utf8(value) => {
let value: &str = match value {
Some(value) => value.as_str(),
None => "null",
};
if matches!(
self.conversion_type,
ConversionType::StringLower | ConversionType::StringUpper
) {
self.format_string(string, value)
} else {
exec_err!(
"Invalid conversion type: {:?} for Utf8",
self.conversion_type
)
}
}
ScalarValue::LargeUtf8(value) => {
let value: &str = match value {
Some(value) => value.as_str(),
None => "null",
};
if matches!(
self.conversion_type,
ConversionType::StringLower | ConversionType::StringUpper
) {
self.format_string(string, value)
} else {
exec_err!(
"Invalid conversion type: {:?} for LargeUtf8",
self.conversion_type
)
}
}
ScalarValue::Utf8View(value) => {
let value: &str = match value {
Some(value) => value.as_str(),
None => "null",
};
self.format_string(string, value)
}
ScalarValue::Decimal128(value, _, scale) => {
match (self.conversion_type, value) {
(
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper,
Some(value),
) => self.format_decimal(string, &value.to_string(), *scale as i64),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_decimal() => {
self.format_string(string, "null")
}
_ => {
exec_err!(
"Invalid conversion type: {:?} for Decimal128",
self.conversion_type
)
}
}
}
ScalarValue::Decimal256(value, _, scale) => {
match (self.conversion_type, value) {
(
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::SciFloatUpper
| ConversionType::CompactFloatLower
| ConversionType::CompactFloatUpper,
Some(value),
) => self.format_decimal(string, &value.to_string(), *scale as i64),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_decimal() => {
self.format_string(string, "null")
}
_ => {
exec_err!(
"Invalid conversion type: {:?} for Decimal256",
self.conversion_type
)
}
}
}
ScalarValue::Time32Second(value) => match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, *value as i64 * 1000000000, &None),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Time32Second",
self.conversion_type
)
}
},
ScalarValue::Time32Millisecond(value) => {
match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, *value as i64 * 1000000, &None),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Time32Millisecond",
self.conversion_type
)
}
}
}
ScalarValue::Time64Microsecond(value) => {
match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, *value * 1000, &None),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Time64Microsecond",
self.conversion_type
)
}
}
}
ScalarValue::Time64Nanosecond(value) => match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, *value, &None),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Time64Nanosecond",
self.conversion_type
)
}
},
ScalarValue::TimestampSecond(value, zone) => {
match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, value * 1000000000, zone),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for TimestampSecond",
self.conversion_type
)
}
}
}
ScalarValue::TimestampMillisecond(value, zone) => {
match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, *value * 1000000, zone),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for TimestampMillisecond",
self.conversion_type
)
}
}
}
ScalarValue::TimestampMicrosecond(value, zone) => {
match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, value * 1000, zone),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for timestampmicrosecond",
self.conversion_type
)
}
}
}
ScalarValue::TimestampNanosecond(value, zone) => {
match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_time(string, *value, zone),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for TimestampNanosecond",
self.conversion_type
)
}
}
}
ScalarValue::Date32(value) => match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_date(string, *value as i64),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Date32",
self.conversion_type
)
}
},
ScalarValue::Date64(value) => match (self.conversion_type, value) {
(
ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
Some(value),
) => self.format_date(string, *value),
(
ConversionType::StringLower | ConversionType::StringUpper,
Some(value),
) => self.format_string(string, &value.to_string()),
(t, None) if t.supports_time() => self.format_string(string, "null"),
_ => {
exec_err!(
"Invalid conversion type: {:?} for Date64",
self.conversion_type
)
}
},
ScalarValue::Null => {
let value = "null".to_string();
self.format_string(string, &value)
}
_ => exec_err!("Invalid scalar value: {value}"),
}
}
fn format_hex_float(&self, writer: &mut String, value: f64) -> Result<()> {
// Handle special cases first
let (sign, raw_exponent, mantissa) = value.to_parts();
let is_subnormal = raw_exponent == 0;
let precision = match self.precision {
NumericParam::FromArgument => None,
NumericParam::Literal(p) => Some(p),
};
// Determine if we need to normalize subnormal numbers
// Only normalize when precision is specified and less than full mantissa width
let mantissa_hex_digits = f64::MANTISSA_BITS.div_ceil(4); // 13 for f64
let should_normalize = is_subnormal
&& precision.is_some()
&& precision.unwrap() < mantissa_hex_digits as i32;
let (value, raw_exponent, mantissa) = if should_normalize {
let value = value * f64::SCALEUP;
let (_, raw_exponent, mantissa) = value.to_parts();
(value, raw_exponent, mantissa)
} else {
(value, raw_exponent, mantissa)
};
let mut temp = String::new();
let sign_char = if sign {
"-"
} else if self.force_sign {
"+"
} else if self.space_sign {
" "
} else {
""
};
match value.category() {
FpCategory::Nan => {
write!(&mut temp, "NaN")?;
}
FpCategory::Infinite => {
write!(&mut temp, "{sign_char}Infinity")?;
}
FpCategory::Zero => {
write!(&mut temp, "{sign_char}0x0.0p0")?;
}
_ => {
let bias = i32::from(f64::EXPONENT_BIAS);
// Calculate actual exponent
// For subnormal numbers, the exponent is 1 - bias (not 0 - bias)
let exponent = if is_subnormal && !should_normalize {
1 - bias
} else {
raw_exponent as i32 - bias
};
// Handle precision for rounding
let final_mantissa = if let Some(p) = precision {
if p == 0 {
// For precision 0, we still need at least 1 hex digit
// Round to the nearest integer mantissa value
let shift_distance = f64::MANTISSA_BITS as i32 - 4; // Keep 1 hex digit (4 bits)
let shifted = mantissa >> shift_distance;
let rounding_bits = mantissa & ((1u64 << shift_distance) - 1);
let round_bit = 1u64 << (shift_distance - 1);
// Round to nearest, ties to even
if rounding_bits > round_bit
|| (rounding_bits == round_bit && (shifted & 1) != 0)
{
(shifted + 1) << shift_distance
} else {
shifted << shift_distance
}
} else {
// Apply rounding based on precision
let precision_bits = p * 4; // Each hex digit is 4 bits
let keep_bits = f64::MANTISSA_BITS as i32;
let shift_distance = keep_bits - precision_bits;
if shift_distance > 0 {
let shifted = mantissa >> shift_distance;
let rounding_bits = mantissa & ((1u64 << shift_distance) - 1);
let round_bit = 1u64 << (shift_distance - 1);
// Round to nearest, ties to even
if rounding_bits > round_bit
|| (rounding_bits == round_bit && (shifted & 1) != 0)
{
(shifted + 1) << shift_distance
} else {
shifted << shift_distance
}
} else {
mantissa
}
}
} else {
mantissa
};
if is_subnormal && !should_normalize {
// Original subnormal format: 0x0.xxxp-1022
if precision.is_some() {
// precision >= 13, show as subnormal
let full_hex = format!(
"{:0width$x}",
final_mantissa,
width = mantissa_hex_digits as usize
);
write!(&mut temp, "{sign_char}0x0.{full_hex}p{exponent}")?;
} else {
// No precision specified, show full subnormal
let hex_digits = format!(
"{:0width$x}",
final_mantissa,
width = mantissa_hex_digits as usize
);
write!(&mut temp, "{sign_char}0x0.{hex_digits}p{exponent}")?;
}
} else {
// Normal format or normalized subnormal: 0x1.xxxpN
if let Some(p) = precision {
let p = if p == 0 { 1 } else { p };
let hex_digits = format!("{final_mantissa:x}");
let formatted_digits = if p as usize >= hex_digits.len() {
// Pad with zeros to match precision
format!("{:0<width$}", hex_digits, width = p as usize)
} else {
hex_digits[..p as usize].to_string()
};
write!(
&mut temp,
"{sign_char}0x1.{formatted_digits}p{exponent}"
)?;
} else {
// Default: show all significant digits
let mut hex_digits = format!("{final_mantissa:x}");
hex_digits = trim_trailing_0s_hex(&hex_digits).to_owned();
if hex_digits.is_empty() {
write!(&mut temp, "{sign_char}0x1.0p{exponent}")?;
} else {
write!(&mut temp, "{sign_char}0x1.{hex_digits}p{exponent}")?;
}
}
}
if should_normalize {
let (prefix, exp) = temp.split_once('p').unwrap();
let iexp = exp.parse::<i32>().unwrap() - f64::SCALEUP_POWER as i32;
temp = format!("{prefix}p{iexp}");
}
}
};
if self.conversion_type.is_upper() {
temp = temp.to_ascii_uppercase();
}
let NumericParam::Literal(width) = self.width else {
writer.push_str(&temp);
return Ok(());
};
if self.left_adj {
writer.push_str(&temp);
for _ in temp.len()..width as usize {
writer.push(' ');
}
} else if self.zero_pad && value.is_finite() {
let delimiter = if self.conversion_type.is_upper() {
"0X"
} else {
"0x"
};
let (prefix, suffix) = temp.split_once(delimiter).unwrap();
writer.push_str(prefix);
writer.push_str(delimiter);
for _ in temp.len()..width as usize {
writer.push('0');
}
writer.push_str(suffix);
} else {
while temp.len() < width as usize {
temp = " ".to_owned() + &temp;
}
writer.push_str(&temp);
};
Ok(())
}
fn format_char(&self, writer: &mut String, value: char) -> Result<()> {
let upper = self.conversion_type.is_upper();
match self.conversion_type {
ConversionType::CharLower | ConversionType::CharUpper => {
let NumericParam::Literal(width) = self.width else {
if upper {
writer.push(value.to_ascii_uppercase());
} else {
writer.push(value);
}
return Ok(());
};
let start_len = writer.len();
if self.left_adj {
if upper {
writer.push(value.to_ascii_uppercase());
} else {
writer.push(value);
}
while writer.len() - start_len < width as usize {
writer.push(' ');
}
} else {
while writer.len() - start_len + value.len_utf8() < width as usize {
writer.push(' ');
}
if upper {
writer.push(value.to_ascii_uppercase());
} else {
writer.push(value);
}
}
Ok(())
}
_ => exec_err!(
"Invalid conversion type: {:?} for char",
self.conversion_type
),
}
}
fn format_boolean(&self, writer: &mut String, value: &Option<bool>) -> Result<()> {
let value = value.unwrap_or(false);
let formatted = match self.conversion_type {
ConversionType::BooleanUpper => {
if value {
"TRUE"
} else {
"FALSE"
}
}
ConversionType::BooleanLower => {
if value {
"true"
} else {
"false"
}
}
_ => {
return exec_err!(
"Invalid conversion type: {:?} for boolean array",
self.conversion_type
);
}
};
self.format_str(writer, formatted)
}
fn format_float(&self, writer: &mut String, value: f64) -> Result<()> {
let mut prefix = String::new();
let mut suffix = String::new();
let mut number = String::new();
let upper = self.conversion_type.is_upper();
// set up the sign
if value.is_sign_negative() {
if self.negative_in_parentheses {
prefix.push('(');
suffix.push(')');
} else {
prefix.push('-');
}
} else if self.space_sign {
prefix.push(' ');
} else if self.force_sign {
prefix.push('+');
}
if value.is_finite() {
let mut use_scientific = false;
let mut strip_trailing_0s = false;
let mut abs = value.abs();
let mut exponent = abs.log10().floor() as i32;
let mut precision = match self.precision {
NumericParam::Literal(p) => p,
_ => 6,
};
match self.conversion_type {
ConversionType::DecFloatLower => {
// default
}
ConversionType::SciFloatLower => {
use_scientific = true;
}
ConversionType::SciFloatUpper => {
use_scientific = true;
}
ConversionType::CompactFloatLower | ConversionType::CompactFloatUpper => {
strip_trailing_0s = true;
if precision == 0 {
precision = 1;
}
// exponent signifies significant digits - we must round now
// to (re)calculate the exponent
let rounding_factor =
10.0_f64.powf((precision - 1 - exponent) as f64);
let rounded_fixed = (abs * rounding_factor).round();
abs = rounded_fixed / rounding_factor;
exponent = abs.log10().floor() as i32;
if exponent < -4 || exponent >= precision {
use_scientific = true;
precision -= 1;
} else {
// precision specifies the number of significant digits
precision -= 1 + exponent;
}
}
_ => {
return exec_err!(
"Invalid conversion type: {:?} for float",
self.conversion_type
);
}
}
if use_scientific {
// Manual scientific notation formatting for uppercase E
let mantissa = abs / 10.0_f64.powf(exponent as f64);
let exp_char = if upper { 'E' } else { 'e' };
number = format!("{mantissa:.prec$}", prec = precision as usize);
if strip_trailing_0s {
number = trim_trailing_0s(&number).to_owned();
}
number = format!("{number}{exp_char}{exponent:+03}");
} else {
number = format!("{abs:.prec$}", prec = precision as usize);
if strip_trailing_0s {
number = trim_trailing_0s(&number).to_owned();
}
}
if self.alt_form && !number.contains('.') {
number += ".";
}
} else {
// not finite
match self.conversion_type {
ConversionType::DecFloatLower
| ConversionType::SciFloatLower
| ConversionType::CompactFloatLower => {
if value.is_infinite() {
number.push_str("Infinity")
} else {
number.push_str("NaN")
}
}
ConversionType::SciFloatUpper | ConversionType::CompactFloatUpper => {
if value.is_infinite() {
number.push_str("INFINITY")
} else {
number.push_str("NAN")
}
}
_ => {
return exec_err!(
"Invalid conversion type: {:?} for float",
self.conversion_type
);
}
}
}
// Take care of padding
let NumericParam::Literal(width) = self.width else {
writer.push_str(&prefix);
writer.push_str(&number);
writer.push_str(&suffix);
return Ok(());
};
if self.left_adj {
let mut full_num = prefix + &number + &suffix;
while full_num.len() < width as usize {
full_num.push(' ');
}
writer.push_str(&full_num);
} else if self.zero_pad && value.is_finite() {
while prefix.len() + number.len() + suffix.len() < width as usize {
prefix.push('0');
}
writer.push_str(&prefix);
writer.push_str(&number);
writer.push_str(&suffix);
} else {
let mut full_num = prefix + &number + &suffix;
while full_num.len() < width as usize {
full_num = " ".to_owned() + &full_num;
}
writer.push_str(&full_num);
};
Ok(())
}
fn format_signed(&self, writer: &mut String, value: i64) -> Result<()> {
let negative = value < 0;
let abs_val = value.abs();
let (sign_prefix, sign_suffix) = if negative && self.negative_in_parentheses {
("(".to_owned(), ")".to_owned())
} else if negative {
("-".to_owned(), "".to_owned())
} else if self.force_sign {
("+".to_owned(), "".to_owned())
} else if self.space_sign {
(" ".to_owned(), "".to_owned())
} else {
("".to_owned(), "".to_owned())
};
let mut mod_spec = *self;
mod_spec.width = match self.width {
NumericParam::Literal(w) => NumericParam::Literal(
w - sign_prefix.len() as i32 - sign_suffix.len() as i32,
),
_ => NumericParam::FromArgument,
};
let mut formatted = String::new();
mod_spec.format_unsigned(&mut formatted, abs_val as u64)?;
// put the sign a after any leading spaces
let mut actual_number = &formatted[0..];
let mut leading_spaces = &formatted[0..0];
if let Some(first_non_space) = formatted.find(|c| c != ' ') {
actual_number = &formatted[first_non_space..];
leading_spaces = &formatted[0..first_non_space];
}
write!(
writer,
"{}{}{}{}",
leading_spaces.to_owned(),
sign_prefix,
actual_number,
sign_suffix
)
.map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
Ok(())
}
fn format_unsigned(&self, writer: &mut String, value: u64) -> Result<()> {
let mut s = String::new();
let mut alt_prefix = "";
match self.conversion_type {
ConversionType::DecInt => {
let num_str = format!("{value}");
if self.grouping_separator {
// Add thousands separators
let mut result = String::new();
let chars: Vec<char> = num_str.chars().collect();
for (i, c) in chars.iter().enumerate() {
if i > 0 && (chars.len() - i).is_multiple_of(3) {
result.push(',');
}
result.push(*c);
}
s = result;
} else {
s = num_str;
}
}
ConversionType::HexIntLower => {
alt_prefix = "0x";
write!(&mut s, "{value:x}")
.map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
}
ConversionType::HexIntUpper => {
alt_prefix = "0X";
write!(&mut s, "{value:X}")
.map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
}
ConversionType::OctInt => {
alt_prefix = "0";
write!(&mut s, "{value:o}")
.map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
}
_ => {
return exec_err!(
"Invalid conversion type: {:?} for u64",
self.conversion_type
);
}
}
let mut prefix = if self.alt_form {
alt_prefix.to_owned()
} else {
String::new()
};
let formatted = if let NumericParam::Literal(width) = self.width {
if self.left_adj {
let mut num_str = prefix + &s;
while num_str.len() < width as usize {
num_str.push(' ');
}
num_str
} else if self.zero_pad {
while prefix.len() + s.len() < width as usize {
prefix.push('0');
}
prefix + &s
} else {
let mut num_str = prefix + &s;
while num_str.len() < width as usize {
num_str = " ".to_owned() + &num_str;
}
num_str
}
} else {
prefix + &s
};
write!(writer, "{formatted}")
.map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
Ok(())
}
fn format_str(&self, writer: &mut String, value: &str) -> Result<()> {
// Take care of precision, putting the truncated string in `content`
let precision: usize = match self.precision {
NumericParam::Literal(p) => p,
_ => i32::MAX,
}
.try_into()
.unwrap_or_default();
let content_len = {
let mut content_len = precision.min(value.len());
while !value.is_char_boundary(content_len) {
content_len -= 1;
}
content_len
};
let content = &value[..content_len];
// Pad to width if needed, putting the padded string in `s`
if let NumericParam::Literal(width) = self.width {
let start_len = writer.len();
if self.left_adj {
writer.push_str(content);
while writer.len() - start_len < width as usize {
writer.push(' ');
}
} else {
while writer.len() - start_len + content.len() < width as usize {
writer.push(' ');
}
writer.push_str(content);
}
} else {
writer.push_str(content);
}
Ok(())
}
fn format_string(&self, writer: &mut String, value: &str) -> Result<()> {
if self.conversion_type.is_upper() {
let upper = value.to_ascii_uppercase();
self.format_str(writer, &upper)
} else {
self.format_str(writer, value)
}
}
fn format_decimal(&self, writer: &mut String, value: &str, scale: i64) -> Result<()> {
let mut prefix = String::new();
let upper = self.conversion_type.is_upper();
// Parse as BigDecimal
let decimal = value
.parse::<BigInt>()
.map_err(|e| exec_datafusion_err!("Failed to parse decimal: {}", e))?;
let decimal = BigDecimal::from_bigint(decimal, scale);
// Handle sign
let is_negative = decimal.sign() == Sign::Minus;
let abs_decimal = decimal.abs();
if is_negative {
prefix.push('-');
} else if self.space_sign {
prefix.push(' ');
} else if self.force_sign {
prefix.push('+');
}
let exp_symb = if upper { 'E' } else { 'e' };
let mut strip_trailing_0s = false;
// Get precision setting
let mut precision = match self.precision {
NumericParam::Literal(p) => p,
_ => 6,
};
let number = match self.conversion_type {
ConversionType::DecFloatLower => {
// Format as fixed-point decimal
self.format_decimal_fixed(&abs_decimal, precision, strip_trailing_0s)?
}
ConversionType::SciFloatLower => self.format_decimal_scientific(
&abs_decimal,
precision,
'e',
strip_trailing_0s,
)?,
ConversionType::SciFloatUpper => self.format_decimal_scientific(
&abs_decimal,
precision,
'E',
strip_trailing_0s,
)?,
ConversionType::CompactFloatLower | ConversionType::CompactFloatUpper => {
strip_trailing_0s = true;
if precision == 0 {
precision = 1;
}
// Determine if we should use scientific notation
let log10_val = abs_decimal.to_f64().map(|f| f.log10()).unwrap_or(0.0);
if log10_val < -4.0 || log10_val >= precision as f64 {
self.format_decimal_scientific(
&abs_decimal,
precision - 1,
exp_symb,
strip_trailing_0s,
)?
} else {
self.format_decimal_fixed(
&abs_decimal,
precision - 1 - log10_val.floor() as i32,
strip_trailing_0s,
)?
}
}
_ => {
return exec_err!(
"Invalid conversion type: {:?} for decimal",
self.conversion_type
);
}
};
// Handle padding
let NumericParam::Literal(width) = self.width else {
writer.push_str(&prefix);
writer.push_str(&number);
return Ok(());
};
if self.left_adj {
let mut full_num = prefix + &number;
while full_num.len() < width as usize {
full_num.push(' ');
}
writer.push_str(&full_num);
} else if self.zero_pad {
while prefix.len() + number.len() < width as usize {
prefix.push('0');
}
writer.push_str(&prefix);
writer.push_str(&number);
} else {
let mut full_num = prefix + &number;
while full_num.len() < width as usize {
full_num = " ".to_owned() + &full_num;
}
writer.push_str(&full_num);
}
Ok(())
}
fn format_decimal_fixed(
&self,
decimal: &BigDecimal,
precision: i32,
strip_trailing_0s: bool,
) -> Result<String> {
if precision <= 0 {
Ok(decimal.round(0).to_string())
} else {
// Use BigDecimal's with_scale method for precise decimal formatting
let scaled = decimal.round(precision as i64);
let mut number = scaled.to_string();
if strip_trailing_0s {
number = trim_trailing_0s(&number).to_owned();
}
Ok(number)
}
}
fn format_decimal_scientific(
&self,
decimal: &BigDecimal,
precision: i32,
exp_char: char,
strip_trailing_0s: bool,
) -> Result<String> {
// Convert to f64 for scientific notation (may lose precision for very large numbers)
let float_val = decimal.to_f64().unwrap_or(0.0);
if float_val == 0.0 {
return Ok(format!("0{exp_char}+00"));
}
let abs_val = float_val.abs();
let exponent = abs_val.log10().floor() as i32;
let mantissa = abs_val / 10.0_f64.powf(exponent as f64);
let mut number = if precision <= 0 {
format!("{mantissa:.0}")
} else {
format!("{mantissa:.prec$}", prec = precision as usize)
};
if strip_trailing_0s {
number = trim_trailing_0s(&number).to_owned();
}
Ok(format!("{number}{exp_char}{exponent:+03}"))
}
fn format_time(
&self,
writer: &mut String,
timestamp_nanos: i64,
timezone: &Option<Arc<str>>,
) -> Result<()> {
let upper = self.conversion_type.is_upper();
match &self.conversion_type {
ConversionType::TimeLower(time_format)
| ConversionType::TimeUpper(time_format) => {
let formatted =
self.format_time_component(timestamp_nanos, *time_format, timezone)?;
let result = if upper {
formatted.to_uppercase()
} else {
formatted
};
write!(writer, "{result}")
.map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
Ok(())
}
_ => exec_err!(
"Invalid conversion type for time: {:?}",
self.conversion_type
),
}
}
fn format_date(&self, writer: &mut String, date_days: i64) -> Result<()> {
// Convert days since epoch to timestamp in nanoseconds
let timestamp_nanos = date_days * 24 * 60 * 60 * 1_000_000_000;
self.format_time(writer, timestamp_nanos, &None)
}
fn format_time_component(
&self,
timestamp_nanos: i64,
time_format: TimeFormat,
_timezone: &Option<Arc<str>>,
) -> Result<String> {
// Convert nanoseconds to seconds and nanoseconds remainder
let secs = timestamp_nanos / 1_000_000_000;
let nanos = (timestamp_nanos % 1_000_000_000) as u32;
// Create DateTime from timestamp
let dt = DateTime::<Utc>::from_timestamp(secs, nanos).ok_or_else(|| {
exec_datafusion_err!("Invalid timestamp: {}", timestamp_nanos)
})?;
match time_format {
TimeFormat::HUpper => Ok(format!("{:02}", dt.hour())),
TimeFormat::IUpper => {
let hour_12 = match dt.hour12() {
(true, h) => h, // PM
(false, h) => h, // AM
};
Ok(format!("{hour_12:02}"))
}
TimeFormat::KLower => Ok(format!("{}", dt.hour())),
TimeFormat::LLower => {
let hour_12 = match dt.hour12() {
(true, h) => h, // PM
(false, h) => h, // AM
};
Ok(format!("{hour_12}"))
}
TimeFormat::MUpper => Ok(format!("{:02}", dt.minute())),
TimeFormat::SUpper => Ok(format!("{:02}", dt.second())),
TimeFormat::LUpper => Ok(format!("{:03}", dt.timestamp_millis() % 1000)),
TimeFormat::NUpper => Ok(format!("{:09}", dt.nanosecond())),
TimeFormat::PLower => {
let (is_pm, _) = dt.hour12();
Ok(if is_pm {
"pm".to_string()
} else {
"am".to_string()
})
}
TimeFormat::ZLower => Ok("+0000".to_string()), // UTC timezone offset
TimeFormat::ZUpper => Ok("UTC".to_string()), // UTC timezone name
TimeFormat::SLower => Ok(format!("{}", dt.timestamp())),
TimeFormat::QUpper => Ok(format!("{}", dt.timestamp_millis())),
TimeFormat::BUpper => Ok(dt.format("%B").to_string()), // Full month name
TimeFormat::BLower => Ok(dt.format("%b").to_string()), // Abbreviated month name
TimeFormat::AUpper => Ok(dt.format("%A").to_string()), // Full weekday name
TimeFormat::ALower => Ok(dt.format("%a").to_string()), // Abbreviated weekday name
TimeFormat::CUpper => Ok(format!("{:02}", dt.year() / 100)),
TimeFormat::YUpper => Ok(format!("{:04}", dt.year())),
TimeFormat::YLower => Ok(format!("{:02}", dt.year() % 100)),
TimeFormat::JLower => Ok(format!("{:03}", dt.ordinal())), // Day of year
TimeFormat::MLower => Ok(format!("{:02}", dt.month())),
TimeFormat::DLower => Ok(format!("{:02}", dt.day())),
TimeFormat::ELower => Ok(format!("{}", dt.day())),
TimeFormat::RUpper => Ok(dt.format("%H:%M").to_string()),
TimeFormat::TUpper => Ok(dt.format("%H:%M:%S").to_string()),
TimeFormat::RLower => {
let (is_pm, hour_12) = dt.hour12();
let am_pm = if is_pm { "PM" } else { "AM" };
Ok(format!(
"{:02}:{:02}:{:02} {}",
hour_12,
dt.minute(),
dt.second(),
am_pm
))
}
TimeFormat::DUpper => Ok(dt.format("%m/%d/%y").to_string()),
TimeFormat::FUpper => Ok(dt.format("%Y-%m-%d").to_string()),
TimeFormat::CLower => Ok(dt.format("%a %b %d %H:%M:%S UTC %Y").to_string()),
}
}
}
trait FloatFormattable: std::fmt::Display {
fn category(&self) -> FpCategory;
fn spark_string(&self) -> String {
match self.category() {
FpCategory::Nan => "NaN".to_string(),
FpCategory::Infinite => {
if self.negative() {
"-Infinity".to_string()
} else {
"Infinity".to_string()
}
}
_ => self.to_string(),
}
}
fn negative(&self) -> bool;
}
impl FloatFormattable for f32 {
fn category(&self) -> FpCategory {
self.classify()
}
fn negative(&self) -> bool {
self.is_sign_negative()
}
}
impl FloatFormattable for f64 {
fn category(&self) -> FpCategory {
self.classify()
}
fn negative(&self) -> bool {
self.is_sign_negative()
}
}
trait FloatBits: FloatFormattable {
const MANTISSA_BITS: u8;
const EXPONENT_BIAS: u16;
const SCALEUP_POWER: u8;
const SCALEUP: Self;
fn to_parts(&self) -> (bool, u16, u64);
}
impl FloatBits for f64 {
const MANTISSA_BITS: u8 = 52;
const EXPONENT_BIAS: u16 = 1023;
const SCALEUP_POWER: u8 = 54;
const SCALEUP: f64 = (1_i64 << Self::SCALEUP_POWER) as f64;
fn to_parts(&self) -> (bool, u16, u64) {
let bits = self.to_bits();
let sign: bool = (bits >> 63) == 1;
let exponent = ((bits >> 52) & 0x7FF) as u16;
let mantissa = bits & 0x000F_FFFF_FFFF_FFFF;
(sign, exponent, mantissa)
}
}
fn trim_trailing_0s(number: &str) -> &str {
if number.contains('.') {
for (i, c) in number.chars().rev().enumerate() {
if c != '0' {
return &number[..number.len() - i];
}
}
}
number
}
fn trim_trailing_0s_hex(number: &str) -> &str {
for (i, c) in number.chars().rev().enumerate() {
if c != '0' {
return &number[..number.len() - i];
}
}
number
}
#[cfg(test)]
mod tests {
use super::*;
use arrow::datatypes::DataType::Utf8;
use datafusion_common::Result;
#[test]
fn test_format_string_nullability() -> Result<()> {
let func = FormatStringFunc::new();
let nullable_format: FieldRef = Arc::new(Field::new("fmt", Utf8, true));
let out_nullable = func.return_field_from_args(ReturnFieldArgs {
arg_fields: &[nullable_format],
scalar_arguments: &[None],
})?;
assert!(
out_nullable.is_nullable(),
"format_string(fmt, ...) should be nullable when fmt is nullable"
);
let non_nullable_format: FieldRef = Arc::new(Field::new("fmt", Utf8, false));
let out_non_nullable = func.return_field_from_args(ReturnFieldArgs {
arg_fields: &[non_nullable_format],
scalar_arguments: &[None],
})?;
assert!(
!out_non_nullable.is_nullable(),
"format_string(fmt, ...) should NOT be nullable when fmt is NOT nullable"
);
Ok(())
}
}