Skip to main content

diesel/pg/types/
ranges.rs

1use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
2use core::error::Error;
3use core::ops::Bound;
4use std::io::Write;
5
6use crate::deserialize::{self, Defaultable, FromSql, Queryable};
7use crate::expression::AsExpression;
8use crate::expression::bound::Bound as SqlBound;
9use crate::pg::{Pg, PgTypeMetadata, PgValue};
10use crate::query_builder::bind_collector::ByteWrapper;
11use crate::serialize::{self, IsNull, Output, ToSql};
12use crate::sql_types::*;
13
14// https://github.com/postgres/postgres/blob/113b0045e20d40f726a0a30e33214455e4f1385e/src/include/utils/rangetypes.h#L35-L43
15struct RangeFlags(<RangeFlags as
    ::bitflags::__private::PublicFlags>::Internal);
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy :: min_ident_chars,
clippy :: assign_op_pattern, clippy :: indexing_slicing, clippy ::
same_name_method, clippy :: iter_without_into_iter,)]
const _: () =
    {
        #[repr(transparent)]
        struct InternalBitFlags(u8);
        #[automatically_derived]
        #[doc(hidden)]
        unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::clone::Clone for InternalBitFlags {
            #[inline]
            fn clone(&self) -> InternalBitFlags {
                let _: ::core::clone::AssertParamIsClone<u8>;
                *self
            }
        }
        #[automatically_derived]
        impl ::core::marker::Copy for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::marker::StructuralPartialEq for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::cmp::PartialEq for InternalBitFlags {
            #[inline]
            fn eq(&self, other: &InternalBitFlags) -> bool {
                self.0 == other.0
            }
        }
        #[automatically_derived]
        impl ::core::cmp::Eq for InternalBitFlags {
            #[inline]
            #[doc(hidden)]
            #[coverage(off)]
            fn assert_fields_are_eq(&self) {
                let _: ::core::cmp::AssertParamIsEq<u8>;
            }
        }
        #[automatically_derived]
        impl ::core::cmp::PartialOrd for InternalBitFlags {
            #[inline]
            fn partial_cmp(&self, other: &InternalBitFlags)
                -> ::core::option::Option<::core::cmp::Ordering> {
                ::core::option::Option::Some(::core::cmp::Ord::cmp(self,
                        other))
            }
        }
        #[automatically_derived]
        impl ::core::cmp::Ord for InternalBitFlags {
            #[inline]
            fn cmp(&self, other: &InternalBitFlags) -> ::core::cmp::Ordering {
                ::core::cmp::Ord::cmp(&self.0, &other.0)
            }
        }
        #[automatically_derived]
        impl ::core::hash::Hash for InternalBitFlags {
            #[inline]
            fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
                ::core::hash::Hash::hash(&self.0, state)
            }
        }
        impl RangeFlags {
            pub const EMPTY: Self = Self::from_bits_retain(0x01);
            pub const LB_INC: Self = Self::from_bits_retain(0x02);
            pub const UB_INC: Self = Self::from_bits_retain(0x04);
            pub const LB_INF: Self = Self::from_bits_retain(0x08);
            pub const UB_INF: Self = Self::from_bits_retain(0x10);
            pub const LB_NULL: Self = Self::from_bits_retain(0x20);
            pub const UB_NULL: Self = Self::from_bits_retain(0x40);
            pub const CONTAIN_EMPTY: Self = Self::from_bits_retain(0x80);
        }
        impl ::bitflags::Flags for RangeFlags {
            const FLAGS: &'static [::bitflags::Flag<RangeFlags>] =
                {
                    mod __bitflags_flag_names {
                        use super::*;
                        pub(super) const EMPTY: &'static str = "EMPTY";
                        pub(super) const LB_INC: &'static str = "LB_INC";
                        pub(super) const UB_INC: &'static str = "UB_INC";
                        pub(super) const LB_INF: &'static str = "LB_INF";
                        pub(super) const UB_INF: &'static str = "UB_INF";
                        pub(super) const LB_NULL: &'static str = "LB_NULL";
                        pub(super) const UB_NULL: &'static str = "UB_NULL";
                        pub(super) const CONTAIN_EMPTY: &'static str =
                            "CONTAIN_EMPTY";
                    }
                    &[{
                                    ::bitflags::Flag::new(__bitflags_flag_names::EMPTY,
                                        RangeFlags::EMPTY)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::LB_INC,
                                        RangeFlags::LB_INC)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::UB_INC,
                                        RangeFlags::UB_INC)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::LB_INF,
                                        RangeFlags::LB_INF)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::UB_INF,
                                        RangeFlags::UB_INF)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::LB_NULL,
                                        RangeFlags::LB_NULL)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::UB_NULL,
                                        RangeFlags::UB_NULL)
                                },
                                {
                                    ::bitflags::Flag::new(__bitflags_flag_names::CONTAIN_EMPTY,
                                        RangeFlags::CONTAIN_EMPTY)
                                }]
                };
            type Bits = u8;
            fn bits(&self) -> u8 { RangeFlags::bits(self) }
            fn from_bits_retain(bits: u8) -> RangeFlags {
                RangeFlags::from_bits_retain(bits)
            }
            fn all_named() -> RangeFlags {
                const ALL_NAMED: u8 =
                    {
                        let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
                        let mut i = 0;
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        {
                            {
                                let flag = &<RangeFlags as ::bitflags::Flags>::FLAGS[i];
                                if flag.is_named() {
                                    truncated = truncated | flag.value().bits();
                                }
                                i += 1;
                            }
                        };
                        let _ = i;
                        truncated
                    };
                RangeFlags::from_bits_retain(ALL_NAMED)
            }
        }
        impl ::bitflags::__private::PublicFlags for RangeFlags {
            type Primitive = u8;
            type Internal = InternalBitFlags;
        }
        impl ::bitflags::__private::core::default::Default for
            InternalBitFlags {
            #[inline]
            fn default() -> Self { InternalBitFlags::empty() }
        }
        impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
            fn fmt(&self,
                f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
                -> ::bitflags::__private::core::fmt::Result {
                if self.is_empty() {
                    f.write_fmt(format_args!("{0:#x}",
                            <u8 as ::bitflags::Bits>::EMPTY))
                } else {
                    ::bitflags::__private::core::fmt::Display::fmt(self, f)
                }
            }
        }
        impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
            fn fmt(&self,
                f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
                -> ::bitflags::__private::core::fmt::Result {
                ::bitflags::parser::to_writer(&RangeFlags(*self), f)
            }
        }
        impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
            type Err = ::bitflags::parser::ParseError;
            fn from_str(s: &str)
                ->
                    ::bitflags::__private::core::result::Result<Self,
                    Self::Err> {
                ::bitflags::parser::from_str::<RangeFlags>(s).map(|flags|
                        flags.0)
            }
        }
        impl ::bitflags::__private::core::convert::AsRef<u8> for
            InternalBitFlags {
            fn as_ref(&self) -> &u8 { &self.0 }
        }
        impl ::bitflags::__private::core::convert::From<u8> for
            InternalBitFlags {
            fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
        }
        impl InternalBitFlags {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self {
                Self(<u8 as ::bitflags::Bits>::EMPTY)
            }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self {
                let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
                let mut i = 0;
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <RangeFlags as ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                let _ = i;
                Self(truncated)
            }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0 }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                let truncated = Self::from_bits_truncate(bits).0;
                if truncated == bits {
                    ::bitflags::__private::core::option::Option::Some(Self(bits))
                } else { ::bitflags::__private::core::option::Option::None }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(bits & Self::all().0)
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                mod __bitflags_flag_names {
                    use super::*;
                    pub(super) const EMPTY: &'static str = "EMPTY";
                    pub(super) const LB_INC: &'static str = "LB_INC";
                    pub(super) const UB_INC: &'static str = "UB_INC";
                    pub(super) const LB_INF: &'static str = "LB_INF";
                    pub(super) const UB_INF: &'static str = "UB_INF";
                    pub(super) const LB_NULL: &'static str = "LB_NULL";
                    pub(super) const UB_NULL: &'static str = "UB_NULL";
                    pub(super) const CONTAIN_EMPTY: &'static str =
                        "CONTAIN_EMPTY";
                }
                {
                    {
                        if name == __bitflags_flag_names::EMPTY {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::EMPTY.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::LB_INC {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::LB_INC.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::UB_INC {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::UB_INC.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::LB_INF {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::LB_INF.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::UB_INF {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::UB_INF.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::LB_NULL {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::LB_NULL.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::UB_NULL {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::UB_NULL.bits()));
                        }
                    };
                };
                {
                    {
                        if name == __bitflags_flag_names::CONTAIN_EMPTY {
                            return ::bitflags::__private::core::option::Option::Some(Self(RangeFlags::CONTAIN_EMPTY.bits()));
                        }
                    };
                };
                let _ = name;
                ::bitflags::__private::core::option::Option::None
            }
            /// Whether all bits in `self` are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.0 == <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().0 | self.0 == self.0
            }
            /// Whether any set bits in `other` are also set in `self`.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all set bits in `other` are also set in `self`.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0 & other.0 == other.0
            }
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                *self = Self(self.0).union(other);
            }
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                *self = Self(self.0).difference(other);
            }
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                *self = Self(self.0).symmetric_difference(other);
            }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value { self.insert(other); } else { self.remove(other); }
            }
            /// The bitwise and (`&`) of the bits in `self` and `other`.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0 & other.0)
            }
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0)
            }
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0 & !other.0)
            }
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0 ^ other.0)
            }
            /// The bitwise negation (`!`) of the bits in `self`, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.0)
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for InternalBitFlags {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            fn bitor(self, other: InternalBitFlags) -> Self {
                self.union(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for
            InternalBitFlags {
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for
            InternalBitFlags {
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in `self` and `other`.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for
            InternalBitFlags {
            /// The bitwise and (`&`) of the bits in `self` and `other`.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for InternalBitFlags {
            type Output = Self;
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
            {
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in `self`, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
            InternalBitFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<InternalBitFlags>
            for InternalBitFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl InternalBitFlags {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self) -> ::bitflags::iter::Iter<RangeFlags> {
                ::bitflags::iter::Iter::__private_const_new(<RangeFlags as
                        ::bitflags::Flags>::FLAGS,
                    RangeFlags::from_bits_retain(self.bits()),
                    RangeFlags::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<RangeFlags> {
                ::bitflags::iter::IterNames::__private_const_new(<RangeFlags
                        as ::bitflags::Flags>::FLAGS,
                    RangeFlags::from_bits_retain(self.bits()),
                    RangeFlags::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for
            InternalBitFlags {
            type Item = RangeFlags;
            type IntoIter = ::bitflags::iter::Iter<RangeFlags>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
        impl InternalBitFlags {
            /// Returns a mutable reference to the raw value of the flags currently stored.
            #[inline]
            pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
        }
        impl RangeFlags {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self { Self(InternalBitFlags::all()) }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0.bits() }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                match InternalBitFlags::from_bits(bits) {
                    ::bitflags::__private::core::option::Option::Some(bits) =>
                        ::bitflags::__private::core::option::Option::Some(Self(bits)),
                    ::bitflags::__private::core::option::Option::None =>
                        ::bitflags::__private::core::option::Option::None,
                }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(InternalBitFlags::from_bits_truncate(bits))
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self {
                Self(InternalBitFlags::from_bits_retain(bits))
            }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                match InternalBitFlags::from_name(name) {
                    ::bitflags::__private::core::option::Option::Some(bits) =>
                        ::bitflags::__private::core::option::Option::Some(Self(bits)),
                    ::bitflags::__private::core::option::Option::None =>
                        ::bitflags::__private::core::option::Option::None,
                }
            }
            /// Whether all bits in `self` are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool { self.0.is_empty() }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool { self.0.is_all() }
            /// Whether any set bits in `other` are also set in `self`.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0.intersects(other.0)
            }
            /// Whether all set bits in `other` are also set in `self`.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0.contains(other.0)
            }
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                self.0.set(other.0, value)
            }
            /// The bitwise and (`&`) of the bits in `self` and `other`.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0.intersection(other.0))
            }
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0.union(other.0))
            }
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0.difference(other.0))
            }
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0.symmetric_difference(other.0))
            }
            /// The bitwise negation (`!`) of the bits in `self`, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self(self.0.complement())
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for RangeFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for RangeFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for RangeFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for RangeFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for RangeFlags {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            fn bitor(self, other: RangeFlags) -> Self { self.union(other) }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for RangeFlags {
            /// The bitwise or (`|`) of the bits in `self` and `other`.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for RangeFlags {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for RangeFlags {
            /// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for RangeFlags {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in `self` and `other`.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for RangeFlags {
            /// The bitwise and (`&`) of the bits in `self` and `other`.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for RangeFlags {
            type Output = Self;
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for RangeFlags {
            /// The intersection of `self` with the complement of `other` (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for RangeFlags {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in `self`, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<RangeFlags> for
            RangeFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<RangeFlags> for
            RangeFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl RangeFlags {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self) -> ::bitflags::iter::Iter<RangeFlags> {
                ::bitflags::iter::Iter::__private_const_new(<RangeFlags as
                        ::bitflags::Flags>::FLAGS,
                    RangeFlags::from_bits_retain(self.bits()),
                    RangeFlags::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<RangeFlags> {
                ::bitflags::iter::IterNames::__private_const_new(<RangeFlags
                        as ::bitflags::Flags>::FLAGS,
                    RangeFlags::from_bits_retain(self.bits()),
                    RangeFlags::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for RangeFlags {
            type Item = RangeFlags;
            type IntoIter = ::bitflags::iter::Iter<RangeFlags>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
    };bitflags::bitflags! {
16    struct RangeFlags: u8 {
17        const EMPTY = 0x01;
18        const LB_INC = 0x02;
19        const UB_INC = 0x04;
20        const LB_INF = 0x08;
21        const UB_INF = 0x10;
22        const LB_NULL = 0x20;
23        const UB_NULL = 0x40;
24        const CONTAIN_EMPTY = 0x80;
25    }
26}
27
28macro_rules! range_as_expression {
29    ($ty:ty; $sql_type:ty) => {
30        #[cfg(feature = "postgres_backend")]
31        // this simplifies the macro implementation
32        // as some macro calls use this lifetime
33        #[allow(clippy::extra_unused_lifetimes)]
34        impl<'a, ST: 'static, T> AsExpression<$sql_type> for $ty {
35            type Expression = SqlBound<$sql_type, Self>;
36
37            fn as_expression(self) -> Self::Expression {
38                SqlBound::new(self)
39            }
40        }
41    };
42}
43
44#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for (Bound<T>, Bound<T>) {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!((Bound<T>, Bound<T>); Range<ST>);
45#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for &'a (Bound<T>, Bound<T>)
    {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a (Bound<T>, Bound<T>); Range<ST>);
46#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    (Bound<T>, Bound<T>) {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!((Bound<T>, Bound<T>); Nullable<Range<ST>>);
47#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    &'a (Bound<T>, Bound<T>) {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a (Bound<T>, Bound<T>); Nullable<Range<ST>>);
48
49#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for core::ops::Range<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::Range<T>; Range<ST>);
50#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for &'a core::ops::Range<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::Range<T>; Range<ST>);
51#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    core::ops::Range<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::Range<T>; Nullable<Range<ST>>);
52#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    &'a core::ops::Range<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::Range<T>; Nullable<Range<ST>>);
53
54#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for
    core::ops::RangeInclusive<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeInclusive<T>; Range<ST>);
55#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for
    &'a core::ops::RangeInclusive<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeInclusive<T>; Range<ST>);
56#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    core::ops::RangeInclusive<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeInclusive<T>; Nullable<Range<ST>>);
57#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    &'a core::ops::RangeInclusive<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeInclusive<T>; Nullable<Range<ST>>);
58
59#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for
    core::ops::RangeToInclusive<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeToInclusive<T>; Range<ST>);
60#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for
    &'a core::ops::RangeToInclusive<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeToInclusive<T>; Range<ST>);
61#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    core::ops::RangeToInclusive<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeToInclusive<T>; Nullable<Range<ST>>);
62#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    &'a core::ops::RangeToInclusive<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeToInclusive<T>; Nullable<Range<ST>>);
63
64#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for core::ops::RangeFrom<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeFrom<T>; Range<ST>);
65#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for
    &'a core::ops::RangeFrom<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeFrom<T>; Range<ST>);
66#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    core::ops::RangeFrom<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeFrom<T>; Nullable<Range<ST>>);
67#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    &'a core::ops::RangeFrom<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeFrom<T>; Nullable<Range<ST>>);
68
69#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for core::ops::RangeTo<T> {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeTo<T>; Range<ST>);
70#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Range<ST>> for &'a core::ops::RangeTo<T>
    {
    type Expression = SqlBound<Range<ST>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeTo<T>; Range<ST>);
71#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    core::ops::RangeTo<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(core::ops::RangeTo<T>; Nullable<Range<ST>>);
72#[allow(clippy :: extra_unused_lifetimes)]
impl<'a, ST: 'static, T> AsExpression<Nullable<Range<ST>>> for
    &'a core::ops::RangeTo<T> {
    type Expression = SqlBound<Nullable<Range<ST>>, Self>;
    fn as_expression(self) -> Self::Expression { SqlBound::new(self) }
}range_as_expression!(&'a core::ops::RangeTo<T>; Nullable<Range<ST>>);
73
74#[cfg(feature = "postgres_backend")]
75impl<T, ST> FromSql<Range<ST>, Pg> for (Bound<T>, Bound<T>)
76where
77    T: FromSql<ST, Pg> + Defaultable,
78{
79    fn from_sql(value: PgValue<'_>) -> deserialize::Result<Self> {
80        let mut bytes = value.as_bytes();
81        let flags: RangeFlags = RangeFlags::from_bits_truncate(bytes.read_u8()?);
82        let mut lower_bound = Bound::Unbounded;
83        let mut upper_bound = Bound::Unbounded;
84
85        if flags.contains(RangeFlags::EMPTY) {
86            lower_bound = Bound::Excluded(T::default_value());
87        } else if !flags.contains(RangeFlags::LB_INF) {
88            let elem_size = bytes.read_i32::<NetworkEndian>()?;
89
90            let (elem_bytes, new_bytes) = bytes
91                .split_at_checked(elem_size.try_into()?)
92                .ok_or_else(|| {
93                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Invalid element size: Got {1} elements, but only {0} bytes",
                bytes.len(), elem_size))
    })format!(
94                        "Invalid element size: Got {elem_size} elements, but only {} bytes",
95                        bytes.len()
96                    )
97                })?;
98            bytes = new_bytes;
99            let value = T::from_sql(PgValue::new_internal(elem_bytes, &value))?;
100
101            lower_bound = if flags.contains(RangeFlags::LB_INC) {
102                Bound::Included(value)
103            } else {
104                Bound::Excluded(value)
105            };
106        }
107
108        if flags.contains(RangeFlags::EMPTY) {
109            upper_bound = Bound::Excluded(T::default_value());
110        } else if !flags.contains(RangeFlags::UB_INF) {
111            let _size = bytes.read_i32::<NetworkEndian>()?;
112            let value = T::from_sql(PgValue::new_internal(bytes, &value))?;
113
114            upper_bound = if flags.contains(RangeFlags::UB_INC) {
115                Bound::Included(value)
116            } else {
117                Bound::Excluded(value)
118            };
119        }
120
121        Ok((lower_bound, upper_bound))
122    }
123}
124
125#[cfg(feature = "postgres_backend")]
126impl<T, ST> Queryable<Range<ST>, Pg> for (Bound<T>, Bound<T>)
127where
128    T: FromSql<ST, Pg> + Defaultable,
129{
130    type Row = Self;
131
132    fn build(row: Self) -> deserialize::Result<Self> {
133        Ok(row)
134    }
135}
136
137#[cfg(feature = "postgres_backend")]
138fn to_sql<ST, T>(
139    start: Bound<&T>,
140    end: Bound<&T>,
141    out: &mut Output<'_, '_, Pg>,
142) -> serialize::Result
143where
144    T: ToSql<ST, Pg>,
145{
146    let mut flags = match start {
147        Bound::Included(_) => RangeFlags::LB_INC,
148        Bound::Excluded(_) => RangeFlags::empty(),
149        Bound::Unbounded => RangeFlags::LB_INF,
150    };
151
152    flags |= match end {
153        Bound::Included(_) => RangeFlags::UB_INC,
154        Bound::Excluded(_) => RangeFlags::empty(),
155        Bound::Unbounded => RangeFlags::UB_INF,
156    };
157
158    out.write_u8(flags.bits())?;
159
160    let mut buffer = Vec::new();
161
162    match start {
163        Bound::Included(ref value) | Bound::Excluded(ref value) => {
164            {
165                let mut inner_buffer = Output::new(ByteWrapper(&mut buffer), out.metadata_lookup());
166                value.to_sql(&mut inner_buffer)?;
167            }
168            out.write_u32::<NetworkEndian>(buffer.len().try_into()?)?;
169            out.write_all(&buffer)?;
170            buffer.clear();
171        }
172        Bound::Unbounded => {}
173    }
174
175    match end {
176        Bound::Included(ref value) | Bound::Excluded(ref value) => {
177            {
178                let mut inner_buffer = Output::new(ByteWrapper(&mut buffer), out.metadata_lookup());
179                value.to_sql(&mut inner_buffer)?;
180            }
181            out.write_u32::<NetworkEndian>(buffer.len().try_into()?)?;
182            out.write_all(&buffer)?;
183        }
184        Bound::Unbounded => {}
185    }
186
187    Ok(IsNull::No)
188}
189
190#[cfg(feature = "postgres_backend")]
191impl<ST, T> ToSql<Range<ST>, Pg> for (Bound<T>, Bound<T>)
192where
193    T: ToSql<ST, Pg>,
194{
195    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
196        to_sql(self.0.as_ref(), self.1.as_ref(), out)
197    }
198}
199
200use core::ops::RangeBounds;
201macro_rules! range_std_to_sql {
202    ($ty:ty) => {
203        #[cfg(feature = "postgres_backend")]
204        impl<ST, T> ToSql<Range<ST>, Pg> for $ty
205        where
206            ST: 'static,
207            T: ToSql<ST, Pg>,
208        {
209            fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
210                to_sql(self.start_bound(), self.end_bound(), out)
211            }
212        }
213    };
214}
215
216impl<ST, T> ToSql<Range<ST>, Pg> for core::ops::Range<T> where ST: 'static,
    T: ToSql<ST, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        to_sql(self.start_bound(), self.end_bound(), out)
    }
}range_std_to_sql!(core::ops::Range<T>);
217impl<ST, T> ToSql<Range<ST>, Pg> for core::ops::RangeInclusive<T> where
    ST: 'static, T: ToSql<ST, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        to_sql(self.start_bound(), self.end_bound(), out)
    }
}range_std_to_sql!(core::ops::RangeInclusive<T>);
218impl<ST, T> ToSql<Range<ST>, Pg> for core::ops::RangeFrom<T> where
    ST: 'static, T: ToSql<ST, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        to_sql(self.start_bound(), self.end_bound(), out)
    }
}range_std_to_sql!(core::ops::RangeFrom<T>);
219impl<ST, T> ToSql<Range<ST>, Pg> for core::ops::RangeTo<T> where ST: 'static,
    T: ToSql<ST, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        to_sql(self.start_bound(), self.end_bound(), out)
    }
}range_std_to_sql!(core::ops::RangeTo<T>);
220impl<ST, T> ToSql<Range<ST>, Pg> for core::ops::RangeToInclusive<T> where
    ST: 'static, T: ToSql<ST, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        to_sql(self.start_bound(), self.end_bound(), out)
    }
}range_std_to_sql!(core::ops::RangeToInclusive<T>);
221
222macro_rules! range_to_sql_nullable {
223    ($ty:ty) => {
224        #[cfg(feature = "postgres_backend")]
225        impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for $ty
226        where
227            ST: 'static,
228            $ty: ToSql<Range<ST>, Pg>,
229        {
230            fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
231                ToSql::<Range<ST>, Pg>::to_sql(self, out)
232            }
233        }
234    };
235}
236impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for (Bound<T>, Bound<T>) where
    ST: 'static, (Bound<T>, Bound<T>): ToSql<Range<ST>, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        ToSql::<Range<ST>, Pg>::to_sql(self, out)
    }
}range_to_sql_nullable!((Bound<T>, Bound<T>));
237impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for core::ops::Range<T> where
    ST: 'static, core::ops::Range<T>: ToSql<Range<ST>, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        ToSql::<Range<ST>, Pg>::to_sql(self, out)
    }
}range_to_sql_nullable!(core::ops::Range<T>);
238impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for core::ops::RangeInclusive<T>
    where ST: 'static, core::ops::RangeInclusive<T>: ToSql<Range<ST>, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        ToSql::<Range<ST>, Pg>::to_sql(self, out)
    }
}range_to_sql_nullable!(core::ops::RangeInclusive<T>);
239impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for core::ops::RangeFrom<T> where
    ST: 'static, core::ops::RangeFrom<T>: ToSql<Range<ST>, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        ToSql::<Range<ST>, Pg>::to_sql(self, out)
    }
}range_to_sql_nullable!(core::ops::RangeFrom<T>);
240impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for core::ops::RangeTo<T> where
    ST: 'static, core::ops::RangeTo<T>: ToSql<Range<ST>, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        ToSql::<Range<ST>, Pg>::to_sql(self, out)
    }
}range_to_sql_nullable!(core::ops::RangeTo<T>);
241impl<ST, T> ToSql<Nullable<Range<ST>>, Pg> for core::ops::RangeToInclusive<T>
    where ST: 'static, core::ops::RangeToInclusive<T>: ToSql<Range<ST>, Pg> {
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>)
        -> serialize::Result {
        ToSql::<Range<ST>, Pg>::to_sql(self, out)
    }
}range_to_sql_nullable!(core::ops::RangeToInclusive<T>);
242
243#[cfg(feature = "postgres_backend")]
244impl HasSqlType<Int4range> for Pg {
245    fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {
246        PgTypeMetadata::new(3904, 3905)
247    }
248}
249
250#[cfg(feature = "postgres_backend")]
251impl HasSqlType<Numrange> for Pg {
252    fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {
253        PgTypeMetadata::new(3906, 3907)
254    }
255}
256
257impl HasSqlType<Tsrange> for Pg {
258    fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {
259        PgTypeMetadata::new(3908, 3909)
260    }
261}
262
263#[cfg(feature = "postgres_backend")]
264impl HasSqlType<Tstzrange> for Pg {
265    fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {
266        PgTypeMetadata::new(3910, 3911)
267    }
268}
269
270#[cfg(feature = "postgres_backend")]
271impl HasSqlType<Daterange> for Pg {
272    fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {
273        PgTypeMetadata::new(3912, 3913)
274    }
275}
276
277#[cfg(feature = "postgres_backend")]
278impl HasSqlType<Int8range> for Pg {
279    fn metadata(_: &mut Self::MetadataLookup) -> PgTypeMetadata {
280        PgTypeMetadata::new(3926, 3927)
281    }
282}
283
284#[cfg(feature = "postgres_backend")]
285impl ToSql<RangeBoundEnum, Pg> for RangeBound {
286    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
287        let literal = match self {
288            Self::LowerBoundInclusiveUpperBoundInclusive => "[]",
289            Self::LowerBoundInclusiveUpperBoundExclusive => "[)",
290            Self::LowerBoundExclusiveUpperBoundInclusive => "(]",
291            Self::LowerBoundExclusiveUpperBoundExclusive => "()",
292        };
293        out.write_all(literal.as_bytes())
294            .map(|_| IsNull::No)
295            .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use crate::deserialize::FromSql;
302    use crate::pg::Pg;
303    use crate::pg::PgValue;
304    use crate::pg::types::ranges::RangeFlags;
305    use crate::sql_types::{Integer, Range};
306    use byteorder::{NetworkEndian, WriteBytesExt};
307    use std::ops::Bound;
308
309    #[test]
310    fn check_invalid_element_size_for_range() {
311        // check for the wrong element size
312        let mut value = Vec::<u8>::new();
313
314        // flags
315        value.write_u8(RangeFlags::empty().bits()).unwrap();
316        // elem size
317        value.write_i32::<NetworkEndian>(6).unwrap();
318        value.write_i32::<NetworkEndian>(42).unwrap();
319
320        let value = PgValue::for_test(&value);
321        let res = <(Bound<i32>, Bound<i32>) as FromSql<Range<Integer>, Pg>>::from_sql(value);
322        assert!(res.is_err());
323        assert_eq!(
324            format!("{}", res.unwrap_err()),
325            "Invalid element size: Got 6 elements, but only 4 bytes"
326        );
327    }
328}