arrow_array/
types.rs

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
// 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.

//! Zero-sized types used to parameterize generic array implementations

use crate::delta::{
    add_days_datetime, add_months_datetime, shift_months, sub_days_datetime, sub_months_datetime,
};
use crate::temporal_conversions::as_datetime_with_timezone;
use crate::timezone::Tz;
use crate::{ArrowNativeTypeOp, OffsetSizeTrait};
use arrow_buffer::{i256, Buffer, OffsetBuffer};
use arrow_data::decimal::{validate_decimal256_precision, validate_decimal_precision};
use arrow_data::{validate_binary_view, validate_string_view};
use arrow_schema::{
    ArrowError, DataType, IntervalUnit, TimeUnit, DECIMAL128_MAX_PRECISION, DECIMAL128_MAX_SCALE,
    DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE, DECIMAL_DEFAULT_SCALE,
};
use chrono::{Duration, NaiveDate, NaiveDateTime};
use half::f16;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::{Add, Sub};

// BooleanType is special: its bit-width is not the size of the primitive type, and its `index`
// operation assumes bit-packing.
/// A boolean datatype
#[derive(Debug)]
pub struct BooleanType {}

impl BooleanType {
    /// The corresponding Arrow data type
    pub const DATA_TYPE: DataType = DataType::Boolean;
}

/// Trait bridging the dynamic-typed nature of Arrow (via [`DataType`]) with the
/// static-typed nature of rust types ([`ArrowNativeType`]) for all types that implement [`ArrowNativeType`].
///
/// [`ArrowNativeType`]: arrow_buffer::ArrowNativeType
pub trait ArrowPrimitiveType: primitive::PrimitiveTypeSealed + 'static {
    /// Corresponding Rust native type for the primitive type.
    type Native: ArrowNativeTypeOp;

    /// the corresponding Arrow data type of this primitive type.
    const DATA_TYPE: DataType;

    /// Returns the byte width of this primitive type.
    fn get_byte_width() -> usize {
        std::mem::size_of::<Self::Native>()
    }

    /// Returns a default value of this primitive type.
    ///
    /// This is useful for aggregate array ops like `sum()`, `mean()`.
    fn default_value() -> Self::Native {
        Default::default()
    }
}

mod primitive {
    pub trait PrimitiveTypeSealed {}
}

macro_rules! make_type {
    ($name:ident, $native_ty:ty, $data_ty:expr, $doc_string: literal) => {
        #[derive(Debug)]
        #[doc = $doc_string]
        pub struct $name {}

        impl ArrowPrimitiveType for $name {
            type Native = $native_ty;
            const DATA_TYPE: DataType = $data_ty;
        }

        impl primitive::PrimitiveTypeSealed for $name {}
    };
}

make_type!(Int8Type, i8, DataType::Int8, "A signed 8-bit integer type.");
make_type!(
    Int16Type,
    i16,
    DataType::Int16,
    "A signed 16-bit integer type."
);
make_type!(
    Int32Type,
    i32,
    DataType::Int32,
    "A signed 32-bit integer type."
);
make_type!(
    Int64Type,
    i64,
    DataType::Int64,
    "A signed 64-bit integer type."
);
make_type!(
    UInt8Type,
    u8,
    DataType::UInt8,
    "An unsigned 8-bit integer type."
);
make_type!(
    UInt16Type,
    u16,
    DataType::UInt16,
    "An unsigned 16-bit integer type."
);
make_type!(
    UInt32Type,
    u32,
    DataType::UInt32,
    "An unsigned 32-bit integer type."
);
make_type!(
    UInt64Type,
    u64,
    DataType::UInt64,
    "An unsigned 64-bit integer type."
);
make_type!(
    Float16Type,
    f16,
    DataType::Float16,
    "A 16-bit floating point number type."
);
make_type!(
    Float32Type,
    f32,
    DataType::Float32,
    "A 32-bit floating point number type."
);
make_type!(
    Float64Type,
    f64,
    DataType::Float64,
    "A 64-bit floating point number type."
);
make_type!(
    TimestampSecondType,
    i64,
    DataType::Timestamp(TimeUnit::Second, None),
    "A timestamp second type with an optional timezone."
);
make_type!(
    TimestampMillisecondType,
    i64,
    DataType::Timestamp(TimeUnit::Millisecond, None),
    "A timestamp millisecond type with an optional timezone."
);
make_type!(
    TimestampMicrosecondType,
    i64,
    DataType::Timestamp(TimeUnit::Microsecond, None),
    "A timestamp microsecond type with an optional timezone."
);
make_type!(
    TimestampNanosecondType,
    i64,
    DataType::Timestamp(TimeUnit::Nanosecond, None),
    "A timestamp nanosecond type with an optional timezone."
);
make_type!(
    Date32Type,
    i32,
    DataType::Date32,
    "A 32-bit date type representing the elapsed time since UNIX epoch in days(32 bits)."
);
make_type!(
    Date64Type,
    i64,
    DataType::Date64,
    "A 64-bit date type representing the elapsed time since UNIX epoch in milliseconds(64 bits)."
);
make_type!(
    Time32SecondType,
    i32,
    DataType::Time32(TimeUnit::Second),
    "A 32-bit time type representing the elapsed time since midnight in seconds."
);
make_type!(
    Time32MillisecondType,
    i32,
    DataType::Time32(TimeUnit::Millisecond),
    "A 32-bit time type representing the elapsed time since midnight in milliseconds."
);
make_type!(
    Time64MicrosecondType,
    i64,
    DataType::Time64(TimeUnit::Microsecond),
    "A 64-bit time type representing the elapsed time since midnight in microseconds."
);
make_type!(
    Time64NanosecondType,
    i64,
    DataType::Time64(TimeUnit::Nanosecond),
    "A 64-bit time type representing the elapsed time since midnight in nanoseconds."
);
make_type!(
    IntervalYearMonthType,
    i32,
    DataType::Interval(IntervalUnit::YearMonth),
    "A “calendar” interval stored as the number of whole months."
);
make_type!(
    IntervalDayTimeType,
    i64,
    DataType::Interval(IntervalUnit::DayTime),
    r#"A “calendar” interval type in days and milliseconds.

## Representation
This type is stored as a single 64 bit integer, interpreted as two i32 fields:
1. the number of elapsed days
2. The number of milliseconds (no leap seconds),

```text
 ┌──────────────┬──────────────┐
 │     Days     │ Milliseconds │
 │  (32 bits)   │  (32 bits)   │
 └──────────────┴──────────────┘
 0              31            63 bit offset
```
Please see the [Arrow Spec](https://github.com/apache/arrow/blob/081b4022fe6f659d8765efc82b3f4787c5039e3c/format/Schema.fbs#L406-L408) for more details

## Note on Comparing and Ordering for Calendar Types

Values of `IntervalDayTimeType` are compared using their binary representation,
which can lead to surprising results. Please see the description of ordering on
[`IntervalMonthDayNanoType`] for more details
"#
);
make_type!(
    IntervalMonthDayNanoType,
    i128,
    DataType::Interval(IntervalUnit::MonthDayNano),
    r#"A “calendar” interval type in months, days, and nanoseconds.

## Representation
This type is stored as a single 128 bit integer,
interpreted as three different signed integral fields:

1. The number of months (32 bits)
2. The number days (32 bits)
2. The number of nanoseconds (64 bits).

Nanoseconds does not allow for leap seconds.
Each field is independent (e.g. there is no constraint that the quantity of
nanoseconds represents less than a day's worth of time).

```text
┌──────────────────────────────┬─────────────┬──────────────┐
│            Nanos             │    Days     │    Months    │
│          (64 bits)           │ (32 bits)   │  (32 bits)   │
└──────────────────────────────┴─────────────┴──────────────┘
  0                            63            95           127 bit offset
```
Please see the [Arrow Spec](https://github.com/apache/arrow/blob/081b4022fe6f659d8765efc82b3f4787c5039e3c/format/Schema.fbs#L409-L415) for more details

## Note on Comparing and Ordering for Calendar Types
Values of `IntervalMonthDayNanoType` are compared using their binary representation,
which can lead to surprising results.

Spans of time measured in calendar units are not fixed in absolute size (e.g.
number of seconds) which makes defining comparisons and ordering non trivial.
For example `1 month` is 28 days for February but `1 month` is 31 days
in December.

This makes the seemingly simple operation of comparing two intervals
complicated in practice. For example is `1 month` more or less than `30 days`? The
answer depends on what month you are talking about.

This crate defines comparisons for calendar types using their binary
representation which is fast and efficient, but leads
to potentially surprising results.

For example a
`IntervalMonthDayNano` of `1 month` will compare as **greater** than a
`IntervalMonthDayNano` of `100 days` because the binary representation of `1 month`
is larger than the binary representation of 100 days.
"#
);
make_type!(
    DurationSecondType,
    i64,
    DataType::Duration(TimeUnit::Second),
    "An elapsed time type in seconds."
);
make_type!(
    DurationMillisecondType,
    i64,
    DataType::Duration(TimeUnit::Millisecond),
    "An elapsed time type in milliseconds."
);
make_type!(
    DurationMicrosecondType,
    i64,
    DataType::Duration(TimeUnit::Microsecond),
    "An elapsed time type in microseconds."
);
make_type!(
    DurationNanosecondType,
    i64,
    DataType::Duration(TimeUnit::Nanosecond),
    "An elapsed time type in nanoseconds."
);

/// A subtype of primitive type that represents legal dictionary keys.
/// See <https://arrow.apache.org/docs/format/Columnar.html>
pub trait ArrowDictionaryKeyType: ArrowPrimitiveType {}

impl ArrowDictionaryKeyType for Int8Type {}

impl ArrowDictionaryKeyType for Int16Type {}

impl ArrowDictionaryKeyType for Int32Type {}

impl ArrowDictionaryKeyType for Int64Type {}

impl ArrowDictionaryKeyType for UInt8Type {}

impl ArrowDictionaryKeyType for UInt16Type {}

impl ArrowDictionaryKeyType for UInt32Type {}

impl ArrowDictionaryKeyType for UInt64Type {}

/// A subtype of primitive type that is used as run-ends index
/// in `RunArray`.
/// See <https://arrow.apache.org/docs/format/Columnar.html>
pub trait RunEndIndexType: ArrowPrimitiveType {}

impl RunEndIndexType for Int16Type {}

impl RunEndIndexType for Int32Type {}

impl RunEndIndexType for Int64Type {}

/// A subtype of primitive type that represents temporal values.
pub trait ArrowTemporalType: ArrowPrimitiveType {}

impl ArrowTemporalType for TimestampSecondType {}
impl ArrowTemporalType for TimestampMillisecondType {}
impl ArrowTemporalType for TimestampMicrosecondType {}
impl ArrowTemporalType for TimestampNanosecondType {}
impl ArrowTemporalType for Date32Type {}
impl ArrowTemporalType for Date64Type {}
impl ArrowTemporalType for Time32SecondType {}
impl ArrowTemporalType for Time32MillisecondType {}
impl ArrowTemporalType for Time64MicrosecondType {}
impl ArrowTemporalType for Time64NanosecondType {}
// impl ArrowTemporalType for IntervalYearMonthType {}
// impl ArrowTemporalType for IntervalDayTimeType {}
// impl ArrowTemporalType for IntervalMonthDayNanoType {}
impl ArrowTemporalType for DurationSecondType {}
impl ArrowTemporalType for DurationMillisecondType {}
impl ArrowTemporalType for DurationMicrosecondType {}
impl ArrowTemporalType for DurationNanosecondType {}

/// A timestamp type allows us to create array builders that take a timestamp.
pub trait ArrowTimestampType: ArrowTemporalType<Native = i64> {
    /// The [`TimeUnit`] of this timestamp.
    const UNIT: TimeUnit;

    /// Returns the `TimeUnit` of this timestamp.
    #[deprecated(note = "Use Self::UNIT")]
    fn get_time_unit() -> TimeUnit {
        Self::UNIT
    }

    /// Creates a ArrowTimestampType::Native from the provided [`NaiveDateTime`]
    ///
    /// See [`DataType::Timestamp`] for more information on timezone handling
    fn make_value(naive: NaiveDateTime) -> Option<i64>;
}

impl ArrowTimestampType for TimestampSecondType {
    const UNIT: TimeUnit = TimeUnit::Second;

    fn make_value(naive: NaiveDateTime) -> Option<i64> {
        Some(naive.and_utc().timestamp())
    }
}
impl ArrowTimestampType for TimestampMillisecondType {
    const UNIT: TimeUnit = TimeUnit::Millisecond;

    fn make_value(naive: NaiveDateTime) -> Option<i64> {
        let utc = naive.and_utc();
        let millis = utc.timestamp().checked_mul(1_000)?;
        millis.checked_add(utc.timestamp_subsec_millis() as i64)
    }
}
impl ArrowTimestampType for TimestampMicrosecondType {
    const UNIT: TimeUnit = TimeUnit::Microsecond;

    fn make_value(naive: NaiveDateTime) -> Option<i64> {
        let utc = naive.and_utc();
        let micros = utc.timestamp().checked_mul(1_000_000)?;
        micros.checked_add(utc.timestamp_subsec_micros() as i64)
    }
}
impl ArrowTimestampType for TimestampNanosecondType {
    const UNIT: TimeUnit = TimeUnit::Nanosecond;

    fn make_value(naive: NaiveDateTime) -> Option<i64> {
        let utc = naive.and_utc();
        let nanos = utc.timestamp().checked_mul(1_000_000_000)?;
        nanos.checked_add(utc.timestamp_subsec_nanos() as i64)
    }
}

fn add_year_months<T: ArrowTimestampType>(
    timestamp: <T as ArrowPrimitiveType>::Native,
    delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
    tz: Tz,
) -> Option<<T as ArrowPrimitiveType>::Native> {
    let months = IntervalYearMonthType::to_months(delta);
    let res = as_datetime_with_timezone::<T>(timestamp, tz)?;
    let res = add_months_datetime(res, months)?;
    let res = res.naive_utc();
    T::make_value(res)
}

fn add_day_time<T: ArrowTimestampType>(
    timestamp: <T as ArrowPrimitiveType>::Native,
    delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
    tz: Tz,
) -> Option<<T as ArrowPrimitiveType>::Native> {
    let (days, ms) = IntervalDayTimeType::to_parts(delta);
    let res = as_datetime_with_timezone::<T>(timestamp, tz)?;
    let res = add_days_datetime(res, days)?;
    let res = res.checked_add_signed(Duration::try_milliseconds(ms as i64)?)?;
    let res = res.naive_utc();
    T::make_value(res)
}

fn add_month_day_nano<T: ArrowTimestampType>(
    timestamp: <T as ArrowPrimitiveType>::Native,
    delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    tz: Tz,
) -> Option<<T as ArrowPrimitiveType>::Native> {
    let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(delta);
    let res = as_datetime_with_timezone::<T>(timestamp, tz)?;
    let res = add_months_datetime(res, months)?;
    let res = add_days_datetime(res, days)?;
    let res = res.checked_add_signed(Duration::nanoseconds(nanos))?;
    let res = res.naive_utc();
    T::make_value(res)
}

fn subtract_year_months<T: ArrowTimestampType>(
    timestamp: <T as ArrowPrimitiveType>::Native,
    delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
    tz: Tz,
) -> Option<<T as ArrowPrimitiveType>::Native> {
    let months = IntervalYearMonthType::to_months(delta);
    let res = as_datetime_with_timezone::<T>(timestamp, tz)?;
    let res = sub_months_datetime(res, months)?;
    let res = res.naive_utc();
    T::make_value(res)
}

fn subtract_day_time<T: ArrowTimestampType>(
    timestamp: <T as ArrowPrimitiveType>::Native,
    delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
    tz: Tz,
) -> Option<<T as ArrowPrimitiveType>::Native> {
    let (days, ms) = IntervalDayTimeType::to_parts(delta);
    let res = as_datetime_with_timezone::<T>(timestamp, tz)?;
    let res = sub_days_datetime(res, days)?;
    let res = res.checked_sub_signed(Duration::try_milliseconds(ms as i64)?)?;
    let res = res.naive_utc();
    T::make_value(res)
}

fn subtract_month_day_nano<T: ArrowTimestampType>(
    timestamp: <T as ArrowPrimitiveType>::Native,
    delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    tz: Tz,
) -> Option<<T as ArrowPrimitiveType>::Native> {
    let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(delta);
    let res = as_datetime_with_timezone::<T>(timestamp, tz)?;
    let res = sub_months_datetime(res, months)?;
    let res = sub_days_datetime(res, days)?;
    let res = res.checked_sub_signed(Duration::nanoseconds(nanos))?;
    let res = res.naive_utc();
    T::make_value(res)
}

impl TimestampSecondType {
    /// Adds the given IntervalYearMonthType to an arrow TimestampSecondType.
    ///
    /// Returns `None` when it will result in overflow.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_year_months::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalDayTimeType to an arrow TimestampSecondType.
    ///
    /// Returns `None` when it will result in overflow.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_day_time::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalMonthDayNanoType to an arrow TimestampSecondType
    ///
    /// Returns `None` when it will result in overflow.
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_month_day_nano::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalYearMonthType to an arrow TimestampSecondType
    ///
    /// Returns `None` when it will result in overflow.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_year_months::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalDayTimeType to an arrow TimestampSecondType
    ///
    /// Returns `None` when it will result in overflow.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_day_time::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalMonthDayNanoType to an arrow TimestampSecondType
    ///
    /// Returns `None` when it will result in overflow.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_month_day_nano::<Self>(timestamp, delta, tz)
    }
}

impl TimestampMicrosecondType {
    /// Adds the given IntervalYearMonthType to an arrow TimestampMicrosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_year_months::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalDayTimeType to an arrow TimestampMicrosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_day_time::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalMonthDayNanoType to an arrow TimestampMicrosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_month_day_nano::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalYearMonthType to an arrow TimestampMicrosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_year_months::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalDayTimeType to an arrow TimestampMicrosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_day_time::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalMonthDayNanoType to an arrow TimestampMicrosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_month_day_nano::<Self>(timestamp, delta, tz)
    }
}

impl TimestampMillisecondType {
    /// Adds the given IntervalYearMonthType to an arrow TimestampMillisecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_year_months::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalDayTimeType to an arrow TimestampMillisecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_day_time::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalMonthDayNanoType to an arrow TimestampMillisecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_month_day_nano::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalYearMonthType to an arrow TimestampMillisecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_year_months::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalDayTimeType to an arrow TimestampMillisecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_day_time::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalMonthDayNanoType to an arrow TimestampMillisecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_month_day_nano::<Self>(timestamp, delta, tz)
    }
}

impl TimestampNanosecondType {
    /// Adds the given IntervalYearMonthType to an arrow TimestampNanosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_year_months::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalDayTimeType to an arrow TimestampNanosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_day_time::<Self>(timestamp, delta, tz)
    }

    /// Adds the given IntervalMonthDayNanoType to an arrow TimestampNanosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn add_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        add_month_day_nano::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalYearMonthType to an arrow TimestampNanosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_year_months(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_year_months::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalDayTimeType to an arrow TimestampNanosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_day_time(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_day_time::<Self>(timestamp, delta, tz)
    }

    /// Subtracts the given IntervalMonthDayNanoType to an arrow TimestampNanosecondType
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The date on which to perform the operation
    /// * `delta` - The interval to add
    /// * `tz` - The timezone in which to interpret `timestamp`
    pub fn subtract_month_day_nano(
        timestamp: <Self as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
        tz: Tz,
    ) -> Option<<Self as ArrowPrimitiveType>::Native> {
        subtract_month_day_nano::<Self>(timestamp, delta, tz)
    }
}

impl IntervalYearMonthType {
    /// Creates a IntervalYearMonthType::Native
    ///
    /// # Arguments
    ///
    /// * `years` - The number of years (+/-) represented in this interval
    /// * `months` - The number of months (+/-) represented in this interval
    #[inline]
    pub fn make_value(
        years: i32,
        months: i32,
    ) -> <IntervalYearMonthType as ArrowPrimitiveType>::Native {
        years * 12 + months
    }

    /// Turns a IntervalYearMonthType type into an i32 of months.
    ///
    /// This operation is technically a no-op, it is included for comprehensiveness.
    ///
    /// # Arguments
    ///
    /// * `i` - The IntervalYearMonthType::Native to convert
    #[inline]
    pub fn to_months(i: <IntervalYearMonthType as ArrowPrimitiveType>::Native) -> i32 {
        i
    }
}

impl IntervalDayTimeType {
    /// Creates a IntervalDayTimeType::Native
    ///
    /// # Arguments
    ///
    /// * `days` - The number of days (+/-) represented in this interval
    /// * `millis` - The number of milliseconds (+/-) represented in this interval
    #[inline]
    pub fn make_value(
        days: i32,
        millis: i32,
    ) -> <IntervalDayTimeType as ArrowPrimitiveType>::Native {
        /*
        https://github.com/apache/arrow/blob/02c8598d264c839a5b5cf3109bfd406f3b8a6ba5/cpp/src/arrow/type.h#L1433
        struct DayMilliseconds {
            int32_t days = 0;
            int32_t milliseconds = 0;
            ...
        }
        64      56      48      40      32      24      16      8       0
        +-------+-------+-------+-------+-------+-------+-------+-------+
        |             days              |         milliseconds          |
        +-------+-------+-------+-------+-------+-------+-------+-------+
        */
        let m = millis as u64 & u32::MAX as u64;
        let d = (days as u64 & u32::MAX as u64) << 32;
        (m | d) as <IntervalDayTimeType as ArrowPrimitiveType>::Native
    }

    /// Turns a IntervalDayTimeType into a tuple of (days, milliseconds)
    ///
    /// # Arguments
    ///
    /// * `i` - The IntervalDayTimeType to convert
    #[inline]
    pub fn to_parts(i: <IntervalDayTimeType as ArrowPrimitiveType>::Native) -> (i32, i32) {
        let days = (i >> 32) as i32;
        let ms = i as i32;
        (days, ms)
    }
}

impl IntervalMonthDayNanoType {
    /// Creates a IntervalMonthDayNanoType::Native
    ///
    /// # Arguments
    ///
    /// * `months` - The number of months (+/-) represented in this interval
    /// * `days` - The number of days (+/-) represented in this interval
    /// * `nanos` - The number of nanoseconds (+/-) represented in this interval
    #[inline]
    pub fn make_value(
        months: i32,
        days: i32,
        nanos: i64,
    ) -> <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native {
        /*
        https://github.com/apache/arrow/blob/02c8598d264c839a5b5cf3109bfd406f3b8a6ba5/cpp/src/arrow/type.h#L1475
        struct MonthDayNanos {
            int32_t months;
            int32_t days;
            int64_t nanoseconds;
        }
        128     112     96      80      64      48      32      16      0
        +-------+-------+-------+-------+-------+-------+-------+-------+
        |     months    |      days     |             nanos             |
        +-------+-------+-------+-------+-------+-------+-------+-------+
        */
        let m = (months as u128 & u32::MAX as u128) << 96;
        let d = (days as u128 & u32::MAX as u128) << 64;
        let n = nanos as u128 & u64::MAX as u128;
        (m | d | n) as <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native
    }

    /// Turns a IntervalMonthDayNanoType into a tuple of (months, days, nanos)
    ///
    /// # Arguments
    ///
    /// * `i` - The IntervalMonthDayNanoType to convert
    #[inline]
    pub fn to_parts(
        i: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    ) -> (i32, i32, i64) {
        let months = (i >> 96) as i32;
        let days = (i >> 64) as i32;
        let nanos = i as i64;
        (months, days, nanos)
    }
}

impl Date32Type {
    /// Converts an arrow Date32Type into a chrono::NaiveDate
    ///
    /// # Arguments
    ///
    /// * `i` - The Date32Type to convert
    pub fn to_naive_date(i: <Date32Type as ArrowPrimitiveType>::Native) -> NaiveDate {
        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
        epoch.add(Duration::try_days(i as i64).unwrap())
    }

    /// Converts a chrono::NaiveDate into an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `d` - The NaiveDate to convert
    pub fn from_naive_date(d: NaiveDate) -> <Date32Type as ArrowPrimitiveType>::Native {
        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
        d.sub(epoch).num_days() as <Date32Type as ArrowPrimitiveType>::Native
    }

    /// Adds the given IntervalYearMonthType to an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to add
    pub fn add_year_months(
        date: <Date32Type as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
    ) -> <Date32Type as ArrowPrimitiveType>::Native {
        let prior = Date32Type::to_naive_date(date);
        let months = IntervalYearMonthType::to_months(delta);
        let posterior = shift_months(prior, months);
        Date32Type::from_naive_date(posterior)
    }

    /// Adds the given IntervalDayTimeType to an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to add
    pub fn add_day_time(
        date: <Date32Type as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
    ) -> <Date32Type as ArrowPrimitiveType>::Native {
        let (days, ms) = IntervalDayTimeType::to_parts(delta);
        let res = Date32Type::to_naive_date(date);
        let res = res.add(Duration::try_days(days as i64).unwrap());
        let res = res.add(Duration::try_milliseconds(ms as i64).unwrap());
        Date32Type::from_naive_date(res)
    }

    /// Adds the given IntervalMonthDayNanoType to an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to add
    pub fn add_month_day_nano(
        date: <Date32Type as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    ) -> <Date32Type as ArrowPrimitiveType>::Native {
        let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(delta);
        let res = Date32Type::to_naive_date(date);
        let res = shift_months(res, months);
        let res = res.add(Duration::try_days(days as i64).unwrap());
        let res = res.add(Duration::nanoseconds(nanos));
        Date32Type::from_naive_date(res)
    }

    /// Subtract the given IntervalYearMonthType to an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to subtract
    pub fn subtract_year_months(
        date: <Date32Type as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
    ) -> <Date32Type as ArrowPrimitiveType>::Native {
        let prior = Date32Type::to_naive_date(date);
        let months = IntervalYearMonthType::to_months(-delta);
        let posterior = shift_months(prior, months);
        Date32Type::from_naive_date(posterior)
    }

    /// Subtract the given IntervalDayTimeType to an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to subtract
    pub fn subtract_day_time(
        date: <Date32Type as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
    ) -> <Date32Type as ArrowPrimitiveType>::Native {
        let (days, ms) = IntervalDayTimeType::to_parts(delta);
        let res = Date32Type::to_naive_date(date);
        let res = res.sub(Duration::try_days(days as i64).unwrap());
        let res = res.sub(Duration::try_milliseconds(ms as i64).unwrap());
        Date32Type::from_naive_date(res)
    }

    /// Subtract the given IntervalMonthDayNanoType to an arrow Date32Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to subtract
    pub fn subtract_month_day_nano(
        date: <Date32Type as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    ) -> <Date32Type as ArrowPrimitiveType>::Native {
        let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(delta);
        let res = Date32Type::to_naive_date(date);
        let res = shift_months(res, -months);
        let res = res.sub(Duration::try_days(days as i64).unwrap());
        let res = res.sub(Duration::nanoseconds(nanos));
        Date32Type::from_naive_date(res)
    }
}

impl Date64Type {
    /// Converts an arrow Date64Type into a chrono::NaiveDate
    ///
    /// # Arguments
    ///
    /// * `i` - The Date64Type to convert
    pub fn to_naive_date(i: <Date64Type as ArrowPrimitiveType>::Native) -> NaiveDate {
        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
        epoch.add(Duration::try_milliseconds(i).unwrap())
    }

    /// Converts a chrono::NaiveDate into an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `d` - The NaiveDate to convert
    pub fn from_naive_date(d: NaiveDate) -> <Date64Type as ArrowPrimitiveType>::Native {
        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
        d.sub(epoch).num_milliseconds() as <Date64Type as ArrowPrimitiveType>::Native
    }

    /// Adds the given IntervalYearMonthType to an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to add
    pub fn add_year_months(
        date: <Date64Type as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
    ) -> <Date64Type as ArrowPrimitiveType>::Native {
        let prior = Date64Type::to_naive_date(date);
        let months = IntervalYearMonthType::to_months(delta);
        let posterior = shift_months(prior, months);
        Date64Type::from_naive_date(posterior)
    }

    /// Adds the given IntervalDayTimeType to an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to add
    pub fn add_day_time(
        date: <Date64Type as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
    ) -> <Date64Type as ArrowPrimitiveType>::Native {
        let (days, ms) = IntervalDayTimeType::to_parts(delta);
        let res = Date64Type::to_naive_date(date);
        let res = res.add(Duration::try_days(days as i64).unwrap());
        let res = res.add(Duration::try_milliseconds(ms as i64).unwrap());
        Date64Type::from_naive_date(res)
    }

    /// Adds the given IntervalMonthDayNanoType to an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to add
    pub fn add_month_day_nano(
        date: <Date64Type as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    ) -> <Date64Type as ArrowPrimitiveType>::Native {
        let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(delta);
        let res = Date64Type::to_naive_date(date);
        let res = shift_months(res, months);
        let res = res.add(Duration::try_days(days as i64).unwrap());
        let res = res.add(Duration::nanoseconds(nanos));
        Date64Type::from_naive_date(res)
    }

    /// Subtract the given IntervalYearMonthType to an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to subtract
    pub fn subtract_year_months(
        date: <Date64Type as ArrowPrimitiveType>::Native,
        delta: <IntervalYearMonthType as ArrowPrimitiveType>::Native,
    ) -> <Date64Type as ArrowPrimitiveType>::Native {
        let prior = Date64Type::to_naive_date(date);
        let months = IntervalYearMonthType::to_months(-delta);
        let posterior = shift_months(prior, months);
        Date64Type::from_naive_date(posterior)
    }

    /// Subtract the given IntervalDayTimeType to an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to subtract
    pub fn subtract_day_time(
        date: <Date64Type as ArrowPrimitiveType>::Native,
        delta: <IntervalDayTimeType as ArrowPrimitiveType>::Native,
    ) -> <Date64Type as ArrowPrimitiveType>::Native {
        let (days, ms) = IntervalDayTimeType::to_parts(delta);
        let res = Date64Type::to_naive_date(date);
        let res = res.sub(Duration::try_days(days as i64).unwrap());
        let res = res.sub(Duration::try_milliseconds(ms as i64).unwrap());
        Date64Type::from_naive_date(res)
    }

    /// Subtract the given IntervalMonthDayNanoType to an arrow Date64Type
    ///
    /// # Arguments
    ///
    /// * `date` - The date on which to perform the operation
    /// * `delta` - The interval to subtract
    pub fn subtract_month_day_nano(
        date: <Date64Type as ArrowPrimitiveType>::Native,
        delta: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
    ) -> <Date64Type as ArrowPrimitiveType>::Native {
        let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(delta);
        let res = Date64Type::to_naive_date(date);
        let res = shift_months(res, -months);
        let res = res.sub(Duration::try_days(days as i64).unwrap());
        let res = res.sub(Duration::nanoseconds(nanos));
        Date64Type::from_naive_date(res)
    }
}

/// Crate private types for Decimal Arrays
///
/// Not intended to be used outside this crate
mod decimal {
    use super::*;

    pub trait DecimalTypeSealed {}
    impl DecimalTypeSealed for Decimal128Type {}
    impl DecimalTypeSealed for Decimal256Type {}
}

/// A trait over the decimal types, used by [`PrimitiveArray`] to provide a generic
/// implementation across the various decimal types
///
/// Implemented by [`Decimal128Type`] and [`Decimal256Type`] for [`Decimal128Array`]
/// and [`Decimal256Array`] respectively
///
/// [`PrimitiveArray`]: crate::array::PrimitiveArray
/// [`Decimal128Array`]: crate::array::Decimal128Array
/// [`Decimal256Array`]: crate::array::Decimal256Array
pub trait DecimalType:
    'static + Send + Sync + ArrowPrimitiveType + decimal::DecimalTypeSealed
{
    /// Width of the type
    const BYTE_LENGTH: usize;
    /// Maximum number of significant digits
    const MAX_PRECISION: u8;
    /// Maximum no of digits after the decimal point (note the scale can be negative)
    const MAX_SCALE: i8;
    /// fn to create its [`DataType`]
    const TYPE_CONSTRUCTOR: fn(u8, i8) -> DataType;
    /// Default values for [`DataType`]
    const DEFAULT_TYPE: DataType;

    /// "Decimal128" or "Decimal256", for use in error messages
    const PREFIX: &'static str;

    /// Formats the decimal value with the provided precision and scale
    fn format_decimal(value: Self::Native, precision: u8, scale: i8) -> String;

    /// Validates that `value` contains no more than `precision` decimal digits
    fn validate_decimal_precision(value: Self::Native, precision: u8) -> Result<(), ArrowError>;
}

/// Validate that `precision` and `scale` are valid for `T`
///
/// Returns an Error if:
/// - `precision` is zero
/// - `precision` is larger than `T:MAX_PRECISION`
/// - `scale` is larger than `T::MAX_SCALE`
/// - `scale` is > `precision`
pub fn validate_decimal_precision_and_scale<T: DecimalType>(
    precision: u8,
    scale: i8,
) -> Result<(), ArrowError> {
    if precision == 0 {
        return Err(ArrowError::InvalidArgumentError(format!(
            "precision cannot be 0, has to be between [1, {}]",
            T::MAX_PRECISION
        )));
    }
    if precision > T::MAX_PRECISION {
        return Err(ArrowError::InvalidArgumentError(format!(
            "precision {} is greater than max {}",
            precision,
            T::MAX_PRECISION
        )));
    }
    if scale > T::MAX_SCALE {
        return Err(ArrowError::InvalidArgumentError(format!(
            "scale {} is greater than max {}",
            scale,
            T::MAX_SCALE
        )));
    }
    if scale > 0 && scale as u8 > precision {
        return Err(ArrowError::InvalidArgumentError(format!(
            "scale {scale} is greater than precision {precision}"
        )));
    }

    Ok(())
}

/// The decimal type for a Decimal128Array
#[derive(Debug)]
pub struct Decimal128Type {}

impl DecimalType for Decimal128Type {
    const BYTE_LENGTH: usize = 16;
    const MAX_PRECISION: u8 = DECIMAL128_MAX_PRECISION;
    const MAX_SCALE: i8 = DECIMAL128_MAX_SCALE;
    const TYPE_CONSTRUCTOR: fn(u8, i8) -> DataType = DataType::Decimal128;
    const DEFAULT_TYPE: DataType =
        DataType::Decimal128(DECIMAL128_MAX_PRECISION, DECIMAL_DEFAULT_SCALE);
    const PREFIX: &'static str = "Decimal128";

    fn format_decimal(value: Self::Native, precision: u8, scale: i8) -> String {
        format_decimal_str(&value.to_string(), precision as usize, scale)
    }

    fn validate_decimal_precision(num: i128, precision: u8) -> Result<(), ArrowError> {
        validate_decimal_precision(num, precision)
    }
}

impl ArrowPrimitiveType for Decimal128Type {
    type Native = i128;

    const DATA_TYPE: DataType = <Self as DecimalType>::DEFAULT_TYPE;
}

impl primitive::PrimitiveTypeSealed for Decimal128Type {}

/// The decimal type for a Decimal256Array
#[derive(Debug)]
pub struct Decimal256Type {}

impl DecimalType for Decimal256Type {
    const BYTE_LENGTH: usize = 32;
    const MAX_PRECISION: u8 = DECIMAL256_MAX_PRECISION;
    const MAX_SCALE: i8 = DECIMAL256_MAX_SCALE;
    const TYPE_CONSTRUCTOR: fn(u8, i8) -> DataType = DataType::Decimal256;
    const DEFAULT_TYPE: DataType =
        DataType::Decimal256(DECIMAL256_MAX_PRECISION, DECIMAL_DEFAULT_SCALE);
    const PREFIX: &'static str = "Decimal256";

    fn format_decimal(value: Self::Native, precision: u8, scale: i8) -> String {
        format_decimal_str(&value.to_string(), precision as usize, scale)
    }

    fn validate_decimal_precision(num: i256, precision: u8) -> Result<(), ArrowError> {
        validate_decimal256_precision(num, precision)
    }
}

impl ArrowPrimitiveType for Decimal256Type {
    type Native = i256;

    const DATA_TYPE: DataType = <Self as DecimalType>::DEFAULT_TYPE;
}

impl primitive::PrimitiveTypeSealed for Decimal256Type {}

fn format_decimal_str(value_str: &str, precision: usize, scale: i8) -> String {
    let (sign, rest) = match value_str.strip_prefix('-') {
        Some(stripped) => ("-", stripped),
        None => ("", value_str),
    };
    let bound = precision.min(rest.len()) + sign.len();
    let value_str = &value_str[0..bound];

    if scale == 0 {
        value_str.to_string()
    } else if scale < 0 {
        let padding = value_str.len() + scale.unsigned_abs() as usize;
        format!("{value_str:0<padding$}")
    } else if rest.len() > scale as usize {
        // Decimal separator is in the middle of the string
        let (whole, decimal) = value_str.split_at(value_str.len() - scale as usize);
        format!("{whole}.{decimal}")
    } else {
        // String has to be padded
        format!("{}0.{:0>width$}", sign, rest, width = scale as usize)
    }
}

/// Crate private types for Byte Arrays
///
/// Not intended to be used outside this crate
pub(crate) mod bytes {
    use super::*;

    pub trait ByteArrayTypeSealed {}
    impl<O: OffsetSizeTrait> ByteArrayTypeSealed for GenericStringType<O> {}
    impl<O: OffsetSizeTrait> ByteArrayTypeSealed for GenericBinaryType<O> {}

    pub trait ByteArrayNativeType: std::fmt::Debug + Send + Sync {
        /// # Safety
        ///
        /// `b` must be a valid byte sequence for `Self`
        unsafe fn from_bytes_unchecked(b: &[u8]) -> &Self;
    }

    impl ByteArrayNativeType for [u8] {
        #[inline]
        unsafe fn from_bytes_unchecked(b: &[u8]) -> &Self {
            b
        }
    }

    impl ByteArrayNativeType for str {
        #[inline]
        unsafe fn from_bytes_unchecked(b: &[u8]) -> &Self {
            std::str::from_utf8_unchecked(b)
        }
    }
}

/// A trait over the variable-size byte array types
///
/// See [Variable Size Binary Layout](https://arrow.apache.org/docs/format/Columnar.html#variable-size-binary-layout)
pub trait ByteArrayType: 'static + Send + Sync + bytes::ByteArrayTypeSealed {
    /// Type of offset i.e i32/i64
    type Offset: OffsetSizeTrait;
    /// Type for representing its equivalent rust type i.e
    /// Utf8Array will have native type has &str
    /// BinaryArray will have type as [u8]
    type Native: bytes::ByteArrayNativeType + AsRef<Self::Native> + AsRef<[u8]> + ?Sized;

    /// "Binary" or "String", for use in error messages
    const PREFIX: &'static str;

    /// Datatype of array elements
    const DATA_TYPE: DataType;

    /// Verifies that every consecutive pair of `offsets` denotes a valid slice of `values`
    fn validate(offsets: &OffsetBuffer<Self::Offset>, values: &Buffer) -> Result<(), ArrowError>;
}

/// [`ByteArrayType`] for string arrays
pub struct GenericStringType<O: OffsetSizeTrait> {
    phantom: PhantomData<O>,
}

impl<O: OffsetSizeTrait> ByteArrayType for GenericStringType<O> {
    type Offset = O;
    type Native = str;
    const PREFIX: &'static str = "String";

    const DATA_TYPE: DataType = if O::IS_LARGE {
        DataType::LargeUtf8
    } else {
        DataType::Utf8
    };

    fn validate(offsets: &OffsetBuffer<Self::Offset>, values: &Buffer) -> Result<(), ArrowError> {
        // Verify that the slice as a whole is valid UTF-8
        let validated = std::str::from_utf8(values).map_err(|e| {
            ArrowError::InvalidArgumentError(format!("Encountered non UTF-8 data: {e}"))
        })?;

        // Verify each offset is at a valid character boundary in this UTF-8 array
        for offset in offsets.iter() {
            let o = offset.as_usize();
            if !validated.is_char_boundary(o) {
                if o < validated.len() {
                    return Err(ArrowError::InvalidArgumentError(format!(
                        "Split UTF-8 codepoint at offset {o}"
                    )));
                }
                return Err(ArrowError::InvalidArgumentError(format!(
                    "Offset of {o} exceeds length of values {}",
                    validated.len()
                )));
            }
        }
        Ok(())
    }
}

/// An arrow utf8 array with i32 offsets
pub type Utf8Type = GenericStringType<i32>;
/// An arrow utf8 array with i64 offsets
pub type LargeUtf8Type = GenericStringType<i64>;

/// [`ByteArrayType`] for binary arrays
pub struct GenericBinaryType<O: OffsetSizeTrait> {
    phantom: PhantomData<O>,
}

impl<O: OffsetSizeTrait> ByteArrayType for GenericBinaryType<O> {
    type Offset = O;
    type Native = [u8];
    const PREFIX: &'static str = "Binary";

    const DATA_TYPE: DataType = if O::IS_LARGE {
        DataType::LargeBinary
    } else {
        DataType::Binary
    };

    fn validate(offsets: &OffsetBuffer<Self::Offset>, values: &Buffer) -> Result<(), ArrowError> {
        // offsets are guaranteed to be monotonically increasing and non-empty
        let max_offset = offsets.last().unwrap().as_usize();
        if values.len() < max_offset {
            return Err(ArrowError::InvalidArgumentError(format!(
                "Maximum offset of {max_offset} is larger than values of length {}",
                values.len()
            )));
        }
        Ok(())
    }
}

/// An arrow binary array with i32 offsets
pub type BinaryType = GenericBinaryType<i32>;
/// An arrow binary array with i64 offsets
pub type LargeBinaryType = GenericBinaryType<i64>;

mod byte_view {
    use crate::types::{BinaryViewType, StringViewType};

    pub trait Sealed: Send + Sync {}
    impl Sealed for StringViewType {}
    impl Sealed for BinaryViewType {}
}

/// A trait over the variable length bytes view array types
pub trait ByteViewType: byte_view::Sealed + 'static + PartialEq + Send + Sync {
    /// If element in array is utf8 encoded string.
    const IS_UTF8: bool;

    /// Datatype of array elements
    const DATA_TYPE: DataType = if Self::IS_UTF8 {
        DataType::Utf8View
    } else {
        DataType::BinaryView
    };

    /// "Binary" or "String", for use in displayed or error messages
    const PREFIX: &'static str;

    /// Type for representing its equivalent rust type i.e
    /// Utf8Array will have native type has &str
    /// BinaryArray will have type as [u8]
    type Native: bytes::ByteArrayNativeType + AsRef<Self::Native> + AsRef<[u8]> + ?Sized;

    /// Type for owned corresponding to `Native`
    type Owned: Debug + Clone + Sync + Send + AsRef<Self::Native>;

    /// Verifies that the provided buffers are valid for this array type
    fn validate(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError>;
}

/// [`ByteViewType`] for string arrays
#[derive(PartialEq)]
pub struct StringViewType {}

impl ByteViewType for StringViewType {
    const IS_UTF8: bool = true;
    const PREFIX: &'static str = "String";

    type Native = str;
    type Owned = String;

    fn validate(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
        validate_string_view(views, buffers)
    }
}

/// [`BinaryViewType`] for string arrays
#[derive(PartialEq)]
pub struct BinaryViewType {}

impl ByteViewType for BinaryViewType {
    const IS_UTF8: bool = false;
    const PREFIX: &'static str = "Binary";
    type Native = [u8];
    type Owned = Vec<u8>;

    fn validate(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
        validate_binary_view(views, buffers)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow_data::{layout, BufferSpec};

    #[test]
    fn month_day_nano_should_roundtrip() {
        let value = IntervalMonthDayNanoType::make_value(1, 2, 3);
        assert_eq!(IntervalMonthDayNanoType::to_parts(value), (1, 2, 3));
    }

    #[test]
    fn month_day_nano_should_roundtrip_neg() {
        let value = IntervalMonthDayNanoType::make_value(-1, -2, -3);
        assert_eq!(IntervalMonthDayNanoType::to_parts(value), (-1, -2, -3));
    }

    #[test]
    fn day_time_should_roundtrip() {
        let value = IntervalDayTimeType::make_value(1, 2);
        assert_eq!(IntervalDayTimeType::to_parts(value), (1, 2));
    }

    #[test]
    fn day_time_should_roundtrip_neg() {
        let value = IntervalDayTimeType::make_value(-1, -2);
        assert_eq!(IntervalDayTimeType::to_parts(value), (-1, -2));
    }

    #[test]
    fn year_month_should_roundtrip() {
        let value = IntervalYearMonthType::make_value(1, 2);
        assert_eq!(IntervalYearMonthType::to_months(value), 14);
    }

    #[test]
    fn year_month_should_roundtrip_neg() {
        let value = IntervalYearMonthType::make_value(-1, -2);
        assert_eq!(IntervalYearMonthType::to_months(value), -14);
    }

    fn test_layout<T: ArrowPrimitiveType>() {
        let layout = layout(&T::DATA_TYPE);

        assert_eq!(layout.buffers.len(), 1);

        let spec = &layout.buffers[0];
        assert_eq!(
            spec,
            &BufferSpec::FixedWidth {
                byte_width: std::mem::size_of::<T::Native>(),
                alignment: std::mem::align_of::<T::Native>(),
            }
        );
    }

    #[test]
    fn test_layouts() {
        test_layout::<Int8Type>();
        test_layout::<Int16Type>();
        test_layout::<Int32Type>();
        test_layout::<Int64Type>();
        test_layout::<UInt8Type>();
        test_layout::<UInt16Type>();
        test_layout::<UInt32Type>();
        test_layout::<UInt64Type>();
        test_layout::<Float16Type>();
        test_layout::<Float32Type>();
        test_layout::<Float64Type>();
        test_layout::<Decimal128Type>();
        test_layout::<Decimal256Type>();
        test_layout::<TimestampNanosecondType>();
        test_layout::<TimestampMillisecondType>();
        test_layout::<TimestampMicrosecondType>();
        test_layout::<TimestampNanosecondType>();
        test_layout::<TimestampSecondType>();
        test_layout::<Date32Type>();
        test_layout::<Date64Type>();
        test_layout::<Time32SecondType>();
        test_layout::<Time32MillisecondType>();
        test_layout::<Time64MicrosecondType>();
        test_layout::<Time64NanosecondType>();
        test_layout::<IntervalMonthDayNanoType>();
        test_layout::<IntervalDayTimeType>();
        test_layout::<IntervalYearMonthType>();
        test_layout::<DurationNanosecondType>();
        test_layout::<DurationMicrosecondType>();
        test_layout::<DurationMillisecondType>();
        test_layout::<DurationSecondType>();
    }
}