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
// 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 crate::arith::derive_arith;
use std::ops::Neg;

/// Value of an IntervalMonthDayNano array
///
///  ## 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
/// ┌───────────────┬─────────────┬─────────────────────────────┐
/// │     Months    │     Days    │            Nanos            │
/// │   (32 bits)   │  (32 bits)  │          (64 bits)          │
/// └───────────────┴─────────────┴─────────────────────────────┘
/// 0            32             64                           128 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 `IntervalMonthDayNano` 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.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[repr(C)]
pub struct IntervalMonthDayNano {
    /// Number of months
    pub months: i32,
    /// Number of days
    pub days: i32,
    /// Number of nanoseconds
    pub nanoseconds: i64,
}

impl IntervalMonthDayNano {
    /// The additive identity i.e. `0`.
    pub const ZERO: Self = Self::new(0, 0, 0);

    /// The multiplicative identity, i.e. `1`.
    pub const ONE: Self = Self::new(1, 1, 1);

    /// The multiplicative inverse, i.e. `-1`.
    pub const MINUS_ONE: Self = Self::new(-1, -1, -1);

    /// The maximum value that can be represented
    pub const MAX: Self = Self::new(i32::MAX, i32::MAX, i64::MAX);

    /// The minimum value that can be represented
    pub const MIN: Self = Self::new(i32::MIN, i32::MIN, i64::MIN);

    /// Create a new [`IntervalMonthDayNano`]
    #[inline]
    pub const fn new(months: i32, days: i32, nanoseconds: i64) -> Self {
        Self {
            months,
            days,
            nanoseconds,
        }
    }

    /// Computes the absolute value
    #[inline]
    pub fn wrapping_abs(self) -> Self {
        Self {
            months: self.months.wrapping_abs(),
            days: self.days.wrapping_abs(),
            nanoseconds: self.nanoseconds.wrapping_abs(),
        }
    }

    /// Computes the absolute value
    #[inline]
    pub fn checked_abs(self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_abs()?,
            days: self.days.checked_abs()?,
            nanoseconds: self.nanoseconds.checked_abs()?,
        })
    }

    /// Negates the value
    #[inline]
    pub fn wrapping_neg(self) -> Self {
        Self {
            months: self.months.wrapping_neg(),
            days: self.days.wrapping_neg(),
            nanoseconds: self.nanoseconds.wrapping_neg(),
        }
    }

    /// Negates the value
    #[inline]
    pub fn checked_neg(self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_neg()?,
            days: self.days.checked_neg()?,
            nanoseconds: self.nanoseconds.checked_neg()?,
        })
    }

    /// Performs wrapping addition
    #[inline]
    pub fn wrapping_add(self, other: Self) -> Self {
        Self {
            months: self.months.wrapping_add(other.months),
            days: self.days.wrapping_add(other.days),
            nanoseconds: self.nanoseconds.wrapping_add(other.nanoseconds),
        }
    }

    /// Performs checked addition
    #[inline]
    pub fn checked_add(self, other: Self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_add(other.months)?,
            days: self.days.checked_add(other.days)?,
            nanoseconds: self.nanoseconds.checked_add(other.nanoseconds)?,
        })
    }

    /// Performs wrapping subtraction
    #[inline]
    pub fn wrapping_sub(self, other: Self) -> Self {
        Self {
            months: self.months.wrapping_sub(other.months),
            days: self.days.wrapping_sub(other.days),
            nanoseconds: self.nanoseconds.wrapping_sub(other.nanoseconds),
        }
    }

    /// Performs checked subtraction
    #[inline]
    pub fn checked_sub(self, other: Self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_sub(other.months)?,
            days: self.days.checked_sub(other.days)?,
            nanoseconds: self.nanoseconds.checked_sub(other.nanoseconds)?,
        })
    }

    /// Performs wrapping multiplication
    #[inline]
    pub fn wrapping_mul(self, other: Self) -> Self {
        Self {
            months: self.months.wrapping_mul(other.months),
            days: self.days.wrapping_mul(other.days),
            nanoseconds: self.nanoseconds.wrapping_mul(other.nanoseconds),
        }
    }

    /// Performs checked multiplication
    pub fn checked_mul(self, other: Self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_mul(other.months)?,
            days: self.days.checked_mul(other.days)?,
            nanoseconds: self.nanoseconds.checked_mul(other.nanoseconds)?,
        })
    }

    /// Performs wrapping division
    #[inline]
    pub fn wrapping_div(self, other: Self) -> Self {
        Self {
            months: self.months.wrapping_div(other.months),
            days: self.days.wrapping_div(other.days),
            nanoseconds: self.nanoseconds.wrapping_div(other.nanoseconds),
        }
    }

    /// Performs checked division
    pub fn checked_div(self, other: Self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_div(other.months)?,
            days: self.days.checked_div(other.days)?,
            nanoseconds: self.nanoseconds.checked_div(other.nanoseconds)?,
        })
    }

    /// Performs wrapping remainder
    #[inline]
    pub fn wrapping_rem(self, other: Self) -> Self {
        Self {
            months: self.months.wrapping_rem(other.months),
            days: self.days.wrapping_rem(other.days),
            nanoseconds: self.nanoseconds.wrapping_rem(other.nanoseconds),
        }
    }

    /// Performs checked remainder
    pub fn checked_rem(self, other: Self) -> Option<Self> {
        Some(Self {
            months: self.months.checked_rem(other.months)?,
            days: self.days.checked_rem(other.days)?,
            nanoseconds: self.nanoseconds.checked_rem(other.nanoseconds)?,
        })
    }

    /// Performs wrapping exponentiation
    #[inline]
    pub fn wrapping_pow(self, exp: u32) -> Self {
        Self {
            months: self.months.wrapping_pow(exp),
            days: self.days.wrapping_pow(exp),
            nanoseconds: self.nanoseconds.wrapping_pow(exp),
        }
    }

    /// Performs checked exponentiation
    #[inline]
    pub fn checked_pow(self, exp: u32) -> Option<Self> {
        Some(Self {
            months: self.months.checked_pow(exp)?,
            days: self.days.checked_pow(exp)?,
            nanoseconds: self.nanoseconds.checked_pow(exp)?,
        })
    }
}

impl Neg for IntervalMonthDayNano {
    type Output = Self;

    #[cfg(debug_assertions)]
    fn neg(self) -> Self::Output {
        self.checked_neg().expect("IntervalMonthDayNano overflow")
    }

    #[cfg(not(debug_assertions))]
    fn neg(self) -> Self::Output {
        self.wrapping_neg()
    }
}

derive_arith!(
    IntervalMonthDayNano,
    Add,
    AddAssign,
    add,
    add_assign,
    wrapping_add,
    checked_add
);
derive_arith!(
    IntervalMonthDayNano,
    Sub,
    SubAssign,
    sub,
    sub_assign,
    wrapping_sub,
    checked_sub
);
derive_arith!(
    IntervalMonthDayNano,
    Mul,
    MulAssign,
    mul,
    mul_assign,
    wrapping_mul,
    checked_mul
);
derive_arith!(
    IntervalMonthDayNano,
    Div,
    DivAssign,
    div,
    div_assign,
    wrapping_div,
    checked_div
);
derive_arith!(
    IntervalMonthDayNano,
    Rem,
    RemAssign,
    rem,
    rem_assign,
    wrapping_rem,
    checked_rem
);

/// Value of an IntervalDayTime array
///
/// ## 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 `IntervalDayTime` are compared using their binary representation,
/// which can lead to surprising results. Please see the description of ordering on
/// [`IntervalMonthDayNano`] for more details
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[repr(C)]
pub struct IntervalDayTime {
    /// Number of days
    pub days: i32,
    /// Number of milliseconds
    pub milliseconds: i32,
}

impl IntervalDayTime {
    /// The additive identity i.e. `0`.
    pub const ZERO: Self = Self::new(0, 0);

    /// The multiplicative identity, i.e. `1`.
    pub const ONE: Self = Self::new(1, 1);

    /// The multiplicative inverse, i.e. `-1`.
    pub const MINUS_ONE: Self = Self::new(-1, -1);

    /// The maximum value that can be represented
    pub const MAX: Self = Self::new(i32::MAX, i32::MAX);

    /// The minimum value that can be represented
    pub const MIN: Self = Self::new(i32::MIN, i32::MIN);

    /// Create a new [`IntervalDayTime`]
    #[inline]
    pub const fn new(days: i32, milliseconds: i32) -> Self {
        Self { days, milliseconds }
    }

    /// Computes the absolute value
    #[inline]
    pub fn wrapping_abs(self) -> Self {
        Self {
            days: self.days.wrapping_abs(),
            milliseconds: self.milliseconds.wrapping_abs(),
        }
    }

    /// Computes the absolute value
    #[inline]
    pub fn checked_abs(self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_abs()?,
            milliseconds: self.milliseconds.checked_abs()?,
        })
    }

    /// Negates the value
    #[inline]
    pub fn wrapping_neg(self) -> Self {
        Self {
            days: self.days.wrapping_neg(),
            milliseconds: self.milliseconds.wrapping_neg(),
        }
    }

    /// Negates the value
    #[inline]
    pub fn checked_neg(self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_neg()?,
            milliseconds: self.milliseconds.checked_neg()?,
        })
    }

    /// Performs wrapping addition
    #[inline]
    pub fn wrapping_add(self, other: Self) -> Self {
        Self {
            days: self.days.wrapping_add(other.days),
            milliseconds: self.milliseconds.wrapping_add(other.milliseconds),
        }
    }

    /// Performs checked addition
    #[inline]
    pub fn checked_add(self, other: Self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_add(other.days)?,
            milliseconds: self.milliseconds.checked_add(other.milliseconds)?,
        })
    }

    /// Performs wrapping subtraction
    #[inline]
    pub fn wrapping_sub(self, other: Self) -> Self {
        Self {
            days: self.days.wrapping_sub(other.days),
            milliseconds: self.milliseconds.wrapping_sub(other.milliseconds),
        }
    }

    /// Performs checked subtraction
    #[inline]
    pub fn checked_sub(self, other: Self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_sub(other.days)?,
            milliseconds: self.milliseconds.checked_sub(other.milliseconds)?,
        })
    }

    /// Performs wrapping multiplication
    #[inline]
    pub fn wrapping_mul(self, other: Self) -> Self {
        Self {
            days: self.days.wrapping_mul(other.days),
            milliseconds: self.milliseconds.wrapping_mul(other.milliseconds),
        }
    }

    /// Performs checked multiplication
    pub fn checked_mul(self, other: Self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_mul(other.days)?,
            milliseconds: self.milliseconds.checked_mul(other.milliseconds)?,
        })
    }

    /// Performs wrapping division
    #[inline]
    pub fn wrapping_div(self, other: Self) -> Self {
        Self {
            days: self.days.wrapping_div(other.days),
            milliseconds: self.milliseconds.wrapping_div(other.milliseconds),
        }
    }

    /// Performs checked division
    pub fn checked_div(self, other: Self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_div(other.days)?,
            milliseconds: self.milliseconds.checked_div(other.milliseconds)?,
        })
    }

    /// Performs wrapping remainder
    #[inline]
    pub fn wrapping_rem(self, other: Self) -> Self {
        Self {
            days: self.days.wrapping_rem(other.days),
            milliseconds: self.milliseconds.wrapping_rem(other.milliseconds),
        }
    }

    /// Performs checked remainder
    pub fn checked_rem(self, other: Self) -> Option<Self> {
        Some(Self {
            days: self.days.checked_rem(other.days)?,
            milliseconds: self.milliseconds.checked_rem(other.milliseconds)?,
        })
    }

    /// Performs wrapping exponentiation
    #[inline]
    pub fn wrapping_pow(self, exp: u32) -> Self {
        Self {
            days: self.days.wrapping_pow(exp),
            milliseconds: self.milliseconds.wrapping_pow(exp),
        }
    }

    /// Performs checked exponentiation
    #[inline]
    pub fn checked_pow(self, exp: u32) -> Option<Self> {
        Some(Self {
            days: self.days.checked_pow(exp)?,
            milliseconds: self.milliseconds.checked_pow(exp)?,
        })
    }
}

impl Neg for IntervalDayTime {
    type Output = Self;

    #[cfg(debug_assertions)]
    fn neg(self) -> Self::Output {
        self.checked_neg().expect("IntervalDayMillisecond overflow")
    }

    #[cfg(not(debug_assertions))]
    fn neg(self) -> Self::Output {
        self.wrapping_neg()
    }
}

derive_arith!(
    IntervalDayTime,
    Add,
    AddAssign,
    add,
    add_assign,
    wrapping_add,
    checked_add
);
derive_arith!(
    IntervalDayTime,
    Sub,
    SubAssign,
    sub,
    sub_assign,
    wrapping_sub,
    checked_sub
);
derive_arith!(
    IntervalDayTime,
    Mul,
    MulAssign,
    mul,
    mul_assign,
    wrapping_mul,
    checked_mul
);
derive_arith!(
    IntervalDayTime,
    Div,
    DivAssign,
    div,
    div_assign,
    wrapping_div,
    checked_div
);
derive_arith!(
    IntervalDayTime,
    Rem,
    RemAssign,
    rem,
    rem_assign,
    wrapping_rem,
    checked_rem
);