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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::any::type_name;
use std::cmp::Ordering;
use std::error::Error;
use std::fmt::{self, Debug, Display};
use std::hash::{Hash, Hasher};

use bitflags::bitflags;
use chrono::{DateTime, NaiveDateTime, Utc};
use dec::OrderedDecimal;
use mz_lowertest::MzReflect;
use mz_proto::{RustType, TryFromProtoError};
use postgres_protocol::types;
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
use tokio_postgres::types::{FromSql, Type as PgType};

use crate::adt::date::Date;
use crate::adt::numeric::Numeric;
use crate::adt::timestamp::CheckedTimestamp;
use crate::scalar::DatumKind;
use crate::Datum;

include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.range.rs"));

bitflags! {
    pub(crate) struct InternalFlags: u8 {
        const EMPTY = 1;
        const LB_INCLUSIVE = 1 << 1;
        const LB_INFINITE = 1 << 2;
        const UB_INCLUSIVE = 1 << 3;
        const UB_INFINITE = 1 << 4;
    }
}

bitflags! {
    pub(crate) struct PgFlags: u8 {
        const EMPTY = 0b0000_0001;
        const LB_INCLUSIVE = 0b0000_0010;
        const UB_INCLUSIVE = 0b0000_0100;
        const LB_INFINITE = 0b0000_1000;
        const UB_INFINITE = 0b0001_0000;
    }
}

/// A range of values along the domain `D`.
///
/// `D` is generic to facilitate interoperating over multiple representation,
/// e.g. `Datum` and `mz_pgrepr::Value`. Because of the latter, we have to
/// "manually derive" traits over `Range`.
///
/// Also notable, is that `Datum`s themselves store ranges as
/// `Range<DatumNested<'a>>`, which lets us avoid unnecessary boxing of the
/// range's finite bounds, which are most often expressed as `Datum`.
pub struct Range<D> {
    /// None value represents empty range
    pub inner: Option<RangeInner<D>>,
}

impl<D: Display> Display for Range<D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.inner {
            None => f.write_str("empty"),
            Some(i) => i.fmt(f),
        }
    }
}

impl<D: Debug> Debug for Range<D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Range").field("inner", &self.inner).finish()
    }
}

impl<D: Clone> Clone for Range<D> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<D: Copy> Copy for Range<D> {}

impl<D: PartialEq> PartialEq for Range<D> {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<D: Eq> Eq for Range<D> {}

impl<D: Ord + PartialOrd> PartialOrd for Range<D> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<D: Ord> Ord for Range<D> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.inner.cmp(&other.inner)
    }
}

impl<D: Hash> Hash for Range<D> {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.inner.hash(hasher)
    }
}

/// Trait alias for traits required for generic range function implementations.
pub trait RangeOps<'a>:
    Debug + Ord + PartialOrd + Eq + PartialEq + TryFrom<Datum<'a>> + Into<Datum<'a>>
where
    <Self as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
{
    /// Increment `self` one step forward, if applicable. Return `None` if
    /// overflows.
    fn step(self) -> Option<Self> {
        Some(self)
    }

    fn unwrap_datum(d: Datum<'a>) -> Self {
        <Self>::try_from(d)
            .unwrap_or_else(|_| panic!("cannot take {} to {}", d, type_name::<Self>()))
    }

    fn err_type_name() -> &'static str;
}

impl<'a> RangeOps<'a> for i32 {
    fn step(self) -> Option<i32> {
        self.checked_add(1)
    }

    fn err_type_name() -> &'static str {
        "integer"
    }
}

impl<'a> RangeOps<'a> for i64 {
    fn step(self) -> Option<i64> {
        self.checked_add(1)
    }

    fn err_type_name() -> &'static str {
        "bigint"
    }
}

impl<'a> RangeOps<'a> for Date {
    fn step(self) -> Option<Date> {
        self.checked_add(1).ok()
    }

    fn err_type_name() -> &'static str {
        "date"
    }
}

impl<'a> RangeOps<'a> for OrderedDecimal<Numeric> {
    fn err_type_name() -> &'static str {
        "numeric"
    }
}

impl<'a> RangeOps<'a> for CheckedTimestamp<NaiveDateTime> {
    fn err_type_name() -> &'static str {
        "timestamp"
    }
}

impl<'a> RangeOps<'a> for CheckedTimestamp<DateTime<Utc>> {
    fn err_type_name() -> &'static str {
        "timestamptz"
    }
}

// Totally generic range implementations.
impl<D> Range<D> {
    /// Create a new range.
    ///
    /// Note that when constructing `Range<Datum<'a>>`, the range must still be
    /// canonicalized. If this becomes a common operation, we should consider
    /// addinga `new_canonical` function that performs both steps.
    pub fn new(inner: Option<(RangeLowerBound<D>, RangeUpperBound<D>)>) -> Range<D> {
        Range {
            inner: inner.map(|(lower, upper)| RangeInner { lower, upper }),
        }
    }

    /// Get the flag bits appropriate to use in our internal (i.e. row) encoding
    /// of range values.
    ///
    /// Note that this differs from the flags appropriate to encode with
    /// Postgres, which has `UB_INFINITE` and `LB_INCLUSIVE` in the alternate
    /// position.
    pub fn internal_flag_bits(&self) -> u8 {
        let mut flags = InternalFlags::empty();

        match &self.inner {
            None => {
                flags.set(InternalFlags::EMPTY, true);
            }
            Some(RangeInner { lower, upper }) => {
                flags.set(InternalFlags::EMPTY, false);
                flags.set(InternalFlags::LB_INFINITE, lower.bound.is_none());
                flags.set(InternalFlags::UB_INFINITE, upper.bound.is_none());
                flags.set(InternalFlags::LB_INCLUSIVE, lower.inclusive);
                flags.set(InternalFlags::UB_INCLUSIVE, upper.inclusive);
            }
        }

        flags.bits()
    }

    /// Get the flag bits appropriate to use in PG-compatible encodings of range
    /// values.
    ///
    /// Note that this differs from the flags appropriate for our internal
    /// encoding, which has `UB_INFINITE` and `LB_INCLUSIVE` in the alternate
    /// position.
    pub fn pg_flag_bits(&self) -> u8 {
        let mut flags = PgFlags::empty();

        match &self.inner {
            None => {
                flags.set(PgFlags::EMPTY, true);
            }
            Some(RangeInner { lower, upper }) => {
                flags.set(PgFlags::EMPTY, false);
                flags.set(PgFlags::LB_INFINITE, lower.bound.is_none());
                flags.set(PgFlags::UB_INFINITE, upper.bound.is_none());
                flags.set(PgFlags::LB_INCLUSIVE, lower.inclusive);
                flags.set(PgFlags::UB_INCLUSIVE, upper.inclusive);
            }
        }

        flags.bits()
    }

    /// Converts `self` from having bounds of type `D` to type `O`, converting
    /// the current bounds using `conv`.
    pub fn into_bounds<F, O>(self, conv: F) -> Range<O>
    where
        F: Fn(D) -> O,
    {
        Range {
            inner: self
                .inner
                .map(|RangeInner::<D> { lower, upper }| RangeInner::<O> {
                    lower: RangeLowerBound {
                        inclusive: lower.inclusive,
                        bound: lower.bound.map(&conv),
                    },
                    upper: RangeUpperBound {
                        inclusive: upper.inclusive,
                        bound: upper.bound.map(&conv),
                    },
                }),
        }
    }
}

/// Range implementations meant to work with `Range<Datum>` and `Range<DatumNested>`.
impl<'a, B: Copy + Ord + PartialOrd + Display + Debug> Range<B>
where
    Datum<'a>: From<B>,
{
    pub fn contains_elem<T: RangeOps<'a>>(&self, elem: &T) -> bool
    where
        <T as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
    {
        match self.inner {
            None => false,
            Some(inner) => inner.lower.satisfied_by(elem) && inner.upper.satisfied_by(elem),
        }
    }

    pub fn contains_range(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (None, None) | (Some(_), None) => true,
            (None, Some(_)) => false,
            (Some(i), Some(j)) => i.lower <= j.lower && j.upper <= i.upper,
        }
    }

    pub fn overlaps(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                let r = match s.cmp(&o) {
                    Ordering::Equal => Ordering::Equal,
                    Ordering::Less => s.upper.range_bound_cmp(&o.lower),
                    Ordering::Greater => o.upper.range_bound_cmp(&s.lower),
                };

                // If smaller upper is >= larger lower, elements overlap.
                matches!(r, Ordering::Greater | Ordering::Equal)
            }
            _ => false,
        }
    }

    pub fn before(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                matches!(s.upper.range_bound_cmp(&o.lower), Ordering::Less)
            }
            _ => false,
        }
    }

    pub fn after(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                matches!(s.lower.range_bound_cmp(&o.upper), Ordering::Greater)
            }
            _ => false,
        }
    }

    pub fn overleft(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                matches!(
                    s.upper.range_bound_cmp(&o.upper),
                    Ordering::Less | Ordering::Equal
                )
            }
            _ => false,
        }
    }

    pub fn overright(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                matches!(
                    s.lower.range_bound_cmp(&o.lower),
                    Ordering::Greater | Ordering::Equal
                )
            }
            _ => false,
        }
    }

    pub fn adjacent(&self, other: &Range<B>) -> bool {
        match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                // Look at each (lower, upper) pair.
                for (lower, upper) in [(s.lower, o.upper), (o.lower, s.upper)] {
                    if let (Some(l), Some(u)) = (lower.bound, upper.bound) {
                        // If ..x](x.. or ..x)[x.., adjacent
                        if lower.inclusive ^ upper.inclusive && l == u {
                            return true;
                        }
                    }
                }
                false
            }
            _ => false,
        }
    }

    pub fn union(&self, other: &Range<B>) -> Result<Range<B>, InvalidRangeError> {
        // Handle self or other being empty
        let (s, o) = match (self.inner, other.inner) {
            (None, None) => return Ok(Range { inner: None }),
            (inner @ Some(_), None) | (None, inner @ Some(_)) => return Ok(Range { inner }),
            (Some(s), Some(o)) => {
                // if not overlapping or adjacent, then result would not present continuity, so error.
                if !(self.overlaps(other) || self.adjacent(other)) {
                    return Err(InvalidRangeError::DiscontiguousUnion);
                }
                (s, o)
            }
        };

        let lower = std::cmp::min(s.lower, o.lower);
        let upper = std::cmp::max(s.upper, o.upper);

        Ok(Range {
            inner: Some(RangeInner { lower, upper }),
        })
    }

    pub fn intersection(&self, other: &Range<B>) -> Range<B> {
        // Handle self or other being empty
        let (s, o) = match (self.inner, other.inner) {
            (Some(s), Some(o)) => {
                if !self.overlaps(other) {
                    return Range { inner: None };
                }

                (s, o)
            }
            _ => return Range { inner: None },
        };

        let lower = std::cmp::max(s.lower, o.lower);
        let upper = std::cmp::min(s.upper, o.upper);

        Range {
            inner: Some(RangeInner { lower, upper }),
        }
    }

    // Function requires canonicalization so must be taken into `Range<Datum>`,
    // which can be taken back into `Range<DatumNested>` by the caller if need
    // be.
    pub fn difference(&self, other: &Range<B>) -> Result<Range<Datum<'a>>, InvalidRangeError> {
        use std::cmp::Ordering::*;

        // Difference op does nothing if no overlap.
        if !self.overlaps(other) {
            return Ok(self.into_bounds(Datum::from));
        }

        let (s, o) = match (self.inner, other.inner) {
            (None, _) | (_, None) => unreachable!("already returned from overlap check"),
            (Some(s), Some(o)) => (s, o),
        };

        let ll = s.lower.cmp(&o.lower);
        let uu = s.upper.cmp(&o.upper);

        let r = match (ll, uu) {
            // `self` totally contains `other`
            (Less, Greater) => return Err(InvalidRangeError::DiscontiguousDifference),
            // `other` totally contains `self`
            (Greater | Equal, Less | Equal) => Range { inner: None },
            (Greater | Equal, Greater) => {
                let lower = RangeBound {
                    inclusive: !o.upper.inclusive,
                    bound: o.upper.bound,
                };
                Range {
                    inner: Some(RangeInner {
                        lower,
                        upper: s.upper,
                    }),
                }
            }
            (Less, Less | Equal) => {
                let upper = RangeBound {
                    inclusive: !o.lower.inclusive,
                    bound: o.lower.bound,
                };
                Range {
                    inner: Some(RangeInner {
                        lower: s.lower,
                        upper,
                    }),
                }
            }
        };

        let mut r = r.into_bounds(Datum::from);

        r.canonicalize()?;

        Ok(r)
    }
}

impl<'a> Range<Datum<'a>> {
    /// Canonicalize the range by PG's heuristics, which are:
    /// - Infinite bounds are always exclusive
    /// - If type has step:
    ///  - Exclusive lower bounds are rewritten as inclusive += step
    ///  - Inclusive lower bounds are rewritten as exclusive += step
    /// - Ranges are empty if lower >= upper after prev. step unless range type
    ///   does not have step and both bounds are inclusive
    ///
    /// # Panics
    /// - If the upper and lower bounds are finite and of different types.
    pub fn canonicalize(&mut self) -> Result<(), InvalidRangeError> {
        let (lower, upper) = match &mut self.inner {
            Some(inner) => (&mut inner.lower, &mut inner.upper),
            None => return Ok(()),
        };

        match (lower.bound, upper.bound) {
            (Some(l), Some(u)) => {
                assert_eq!(
                    DatumKind::from(l),
                    DatumKind::from(u),
                    "finite bounds must be of same type"
                );
                if l > u {
                    return Err(InvalidRangeError::MisorderedRangeBounds);
                }
            }
            _ => {}
        };

        lower.canonicalize()?;
        upper.canonicalize()?;

        // The only way that you have two inclusive bounds with equal value are
        // if type does not have step.
        if !(lower.inclusive && upper.inclusive)
            && lower.bound >= upper.bound
            // None is less than any Some, so only need to check this condition.
            && upper.bound.is_some()
        {
            // emtpy range
            self.inner = None
        }

        Ok(())
    }
}

/// Holds the upper and lower bounds for non-empty ranges.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct RangeInner<B> {
    pub lower: RangeLowerBound<B>,
    pub upper: RangeUpperBound<B>,
}

impl<B: Display> Display for RangeInner<B> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(if self.lower.inclusive { "[" } else { "(" })?;
        self.lower.fmt(f)?;
        f.write_str(",")?;
        Display::fmt(&self.upper, f)?;
        f.write_str(if self.upper.inclusive { "]" } else { ")" })
    }
}

impl<B: Ord> Ord for RangeInner<B> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.lower
            .cmp(&other.lower)
            .then(self.upper.cmp(&other.upper))
    }
}

impl<B: PartialOrd + Ord> PartialOrd for RangeInner<B> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Represents a terminal point of a range.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct RangeBound<B, const UPPER: bool = false> {
    pub inclusive: bool,
    /// None value represents an infinite bound.
    pub bound: Option<B>,
}

impl<const UPPER: bool, D: Display> Display for RangeBound<D, UPPER> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.bound {
            None => Ok(()),
            Some(bound) => bound.fmt(f),
        }
    }
}

impl<const UPPER: bool, D: Ord> Ord for RangeBound<D, UPPER> {
    fn cmp(&self, other: &Self) -> Ordering {
        // 1. Sort by bounds
        let mut cmp = self.bound.cmp(&other.bound);
        // 2. Infinite bounds vs. finite bounds are reversed for uppers.
        if UPPER && other.bound.is_none() ^ self.bound.is_none() {
            cmp = cmp.reverse();
        }
        // 3. Tie break by sorting by inclusivity, which is inverted between
        //    lowers and uppers.
        cmp.then(if self.inclusive == other.inclusive {
            Ordering::Equal
        } else if self.inclusive {
            if UPPER {
                Ordering::Greater
            } else {
                Ordering::Less
            }
        } else if UPPER {
            Ordering::Less
        } else {
            Ordering::Greater
        })
    }
}

impl<const UPPER: bool, D: PartialOrd + Ord> PartialOrd for RangeBound<D, UPPER> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// A `RangeBound` that sorts correctly for use as a lower bound.
pub type RangeLowerBound<B> = RangeBound<B, false>;

/// A `RangeBound` that sorts correctly for use as an upper bound.
pub type RangeUpperBound<B> = RangeBound<B, true>;

// Generic RangeBound implementations meant to work over `RangeBound<Datum,..>`
// and `RangeBound<DatumNested,..>`.
impl<'a, const UPPER: bool, B: Copy + Ord + PartialOrd + Display + Debug> RangeBound<B, UPPER>
where
    Datum<'a>: From<B>,
{
    /// Determines where `elem` lies in relation to the range bound.
    ///
    /// # Panics
    /// - If `self.bound.datum()` is not convertible to `T`.
    fn elem_cmp<T: RangeOps<'a>>(&self, elem: &T) -> Ordering
    where
        <T as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
    {
        match self.bound.map(|bound| <T>::unwrap_datum(bound.into())) {
            None if UPPER => Ordering::Greater,
            None => Ordering::Less,
            Some(bound) => bound.cmp(elem),
        }
    }

    /// Does `elem` satisfy this bound?
    fn satisfied_by<T: RangeOps<'a>>(&self, elem: &T) -> bool
    where
        <T as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
    {
        match self.elem_cmp(elem) {
            // Inclusive always satisfied with equality, regardless of upper or
            // lower.
            Ordering::Equal => self.inclusive,
            // Upper satisfied with values less than itself
            Ordering::Greater => UPPER,
            // Lower satisfied with values greater than itself
            Ordering::Less => !UPPER,
        }
    }

    // Compares two `RangeBound`, which do not need to both be of the same
    // `UPPER`.
    fn range_bound_cmp<const OTHER_UPPER: bool>(
        &self,
        other: &RangeBound<B, OTHER_UPPER>,
    ) -> Ordering {
        if UPPER == OTHER_UPPER {
            return self.cmp(&RangeBound {
                inclusive: other.inclusive,
                bound: other.bound,
            });
        }

        // Handle cases where either are infinite bounds, which have special
        // semantics.
        if self.bound.is_none() || other.bound.is_none() {
            return if UPPER {
                Ordering::Greater
            } else {
                Ordering::Less
            };
        }
        // 1. Sort by bounds
        let cmp = self.bound.cmp(&other.bound);
        // 2. Tie break by sorting by inclusivity, which is inverted between
        //    lowers and uppers.
        cmp.then(if self.inclusive && other.inclusive {
            Ordering::Equal
        } else if UPPER {
            Ordering::Less
        } else {
            Ordering::Greater
        })
    }
}

impl<'a, const UPPER: bool> RangeBound<Datum<'a>, UPPER> {
    /// Create a new `RangeBound` whose value is "infinite" (i.e. None) if `d ==
    /// Datum::Null`, otherwise finite (i.e. Some).
    ///
    /// There is not a corresponding generic implementation of this because
    /// genericizing how to express infinite bounds is less clear.
    pub fn new(d: Datum<'a>, inclusive: bool) -> RangeBound<Datum<'a>, UPPER> {
        RangeBound {
            inclusive,
            bound: match d {
                Datum::Null => None,
                o => Some(o),
            },
        }
    }

    /// Rewrite the bounds to the consistent format. This is absolutely
    /// necessary to perform the correct equality/comparison operations on
    /// types.
    fn canonicalize(&mut self) -> Result<(), InvalidRangeError> {
        Ok(match self.bound {
            None => {
                self.inclusive = false;
            }
            Some(value) => match value {
                d @ Datum::Int32(_) => self.canonicalize_inner::<i32>(d)?,
                d @ Datum::Int64(_) => self.canonicalize_inner::<i64>(d)?,
                d @ Datum::Date(_) => self.canonicalize_inner::<Date>(d)?,
                Datum::Numeric(..) | Datum::Timestamp(..) | Datum::TimestampTz(..) => {}
                d => unreachable!("{d:?} not yet supported in ranges"),
            },
        })
    }

    /// Canonicalize `self`'s representation for types that have discrete steps
    /// between values.
    ///
    /// Continuous values (e.g. timestamps, numeric) must not be
    /// canonicalized.
    fn canonicalize_inner<T: RangeOps<'a>>(&mut self, d: Datum<'a>) -> Result<(), InvalidRangeError>
    where
        <T as TryFrom<Datum<'a>>>::Error: std::fmt::Debug,
    {
        // Upper bounds must be exclusive, lower bounds inclusive
        if UPPER == self.inclusive {
            let cur = <T>::unwrap_datum(d);
            self.bound = Some(
                cur.step()
                    .ok_or_else(|| {
                        InvalidRangeError::CanonicalizationOverflow(T::err_type_name().into())
                    })?
                    .into(),
            );
            self.inclusive = !UPPER;
        }

        Ok(())
    }
}

#[derive(
    Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect,
)]
pub enum InvalidRangeError {
    MisorderedRangeBounds,
    CanonicalizationOverflow(Box<str>),
    InvalidRangeBoundFlags,
    DiscontiguousUnion,
    DiscontiguousDifference,
    NullRangeBoundFlags,
}

impl Display for InvalidRangeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            InvalidRangeError::MisorderedRangeBounds => {
                f.write_str("range lower bound must be less than or equal to range upper bound")
            }
            InvalidRangeError::CanonicalizationOverflow(t) => {
                write!(f, "{} out of range", t)
            }
            InvalidRangeError::InvalidRangeBoundFlags => f.write_str("invalid range bound flags"),
            InvalidRangeError::DiscontiguousUnion => {
                f.write_str("result of range union would not be contiguous")
            }
            InvalidRangeError::DiscontiguousDifference => {
                f.write_str("result of range difference would not be contiguous")
            }
            InvalidRangeError::NullRangeBoundFlags => {
                f.write_str("range constructor flags argument must not be null")
            }
        }
    }
}

impl Error for InvalidRangeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

// Required due to Proto decoding using string as its error type
impl From<InvalidRangeError> for String {
    fn from(e: InvalidRangeError) -> Self {
        e.to_string()
    }
}

impl RustType<ProtoInvalidRangeError> for InvalidRangeError {
    fn into_proto(&self) -> ProtoInvalidRangeError {
        use proto_invalid_range_error::*;
        use Kind::*;
        let kind = match self {
            InvalidRangeError::MisorderedRangeBounds => MisorderedRangeBounds(()),
            InvalidRangeError::CanonicalizationOverflow(s) => {
                CanonicalizationOverflow(s.into_proto())
            }
            InvalidRangeError::InvalidRangeBoundFlags => InvalidRangeBoundFlags(()),
            InvalidRangeError::DiscontiguousUnion => DiscontiguousUnion(()),
            InvalidRangeError::DiscontiguousDifference => DiscontiguousDifference(()),
            InvalidRangeError::NullRangeBoundFlags => NullRangeBoundFlags(()),
        };
        ProtoInvalidRangeError { kind: Some(kind) }
    }

    fn from_proto(proto: ProtoInvalidRangeError) -> Result<Self, TryFromProtoError> {
        use proto_invalid_range_error::Kind::*;
        match proto.kind {
            Some(kind) => Ok(match kind {
                MisorderedRangeBounds(()) => InvalidRangeError::MisorderedRangeBounds,
                CanonicalizationOverflow(s) => {
                    InvalidRangeError::CanonicalizationOverflow(s.into())
                }
                InvalidRangeBoundFlags(()) => InvalidRangeError::InvalidRangeBoundFlags,
                DiscontiguousUnion(()) => InvalidRangeError::DiscontiguousUnion,
                DiscontiguousDifference(()) => InvalidRangeError::DiscontiguousDifference,
                NullRangeBoundFlags(()) => InvalidRangeError::NullRangeBoundFlags,
            }),
            None => Err(TryFromProtoError::missing_field(
                "`ProtoInvalidRangeError::kind`",
            )),
        }
    }
}

pub fn parse_range_bound_flags<'a>(flags: &'a str) -> Result<(bool, bool), InvalidRangeError> {
    let mut flags = flags.chars();

    let lower = match flags.next() {
        Some('(') => false,
        Some('[') => true,
        _ => return Err(InvalidRangeError::InvalidRangeBoundFlags),
    };

    let upper = match flags.next() {
        Some(')') => false,
        Some(']') => true,
        _ => return Err(InvalidRangeError::InvalidRangeBoundFlags),
    };

    match flags.next() {
        Some(_) => Err(InvalidRangeError::InvalidRangeBoundFlags),
        None => Ok((lower, upper)),
    }
}

impl<'a, T: FromSql<'a>> FromSql<'a> for Range<T> {
    fn from_sql(ty: &PgType, raw: &'a [u8]) -> Result<Range<T>, Box<dyn Error + Sync + Send>> {
        let inner_typ = match ty {
            &PgType::INT4_RANGE => PgType::INT4,
            &PgType::INT8_RANGE => PgType::INT8,
            &PgType::DATE_RANGE => PgType::DATE,
            &PgType::NUM_RANGE => PgType::NUMERIC,
            &PgType::TS_RANGE => PgType::TIMESTAMP,
            &PgType::TSTZ_RANGE => PgType::TIMESTAMPTZ,
            _ => unreachable!(),
        };

        let inner = match types::range_from_sql(raw)? {
            types::Range::Empty => None,
            types::Range::Nonempty(lower, upper) => {
                let mut bounds = Vec::with_capacity(2);

                for bound_outer in [lower, upper].into_iter() {
                    let bound = match bound_outer {
                        types::RangeBound::Exclusive(bound)
                        | types::RangeBound::Inclusive(bound) => bound
                            .map(|bound| T::from_sql(&inner_typ, bound))
                            .transpose()?,
                        types::RangeBound::Unbounded => None,
                    };
                    let inclusive = matches!(bound_outer, types::RangeBound::Inclusive(_));
                    bounds.push(RangeBound { bound, inclusive });
                }

                let lower = bounds.remove(0);
                let upper = bounds.remove(0);
                assert!(bounds.is_empty());

                Some(RangeInner {
                    lower,
                    // Rewrite bound in terms of appropriate `UPPER`
                    upper: RangeBound {
                        bound: upper.bound,
                        inclusive: upper.inclusive,
                    },
                })
            }
        };

        Ok(Range { inner })
    }

    fn accepts(ty: &PgType) -> bool {
        matches!(
            ty,
            &PgType::INT4_RANGE
                | &PgType::INT8_RANGE
                | &PgType::DATE_RANGE
                | &PgType::NUM_RANGE
                | &PgType::TS_RANGE
                | &PgType::TSTZ_RANGE
        )
    }
}