use core::ops::RangeInclusive;
use super::{
BuiltinType,
cast::{CastError, CastValue},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum IntegerType {
Smallint,
Integer,
Bigint,
}
impl IntegerType {
#[must_use]
pub fn range(self) -> RangeInclusive<i64> {
match self {
Self::Smallint => i64::from(i16::MIN)..=i64::from(i16::MAX),
Self::Integer => i64::from(i32::MIN)..=i64::from(i32::MAX),
Self::Bigint => i64::MIN..=i64::MAX,
}
}
#[must_use]
pub fn wider(self, other: Self) -> Self {
self.max(other)
}
pub fn value(self, value: i64) -> Result<CastValue, CastError> {
let out_of_range = |_| CastError::OutOfRange(self.into());
match self {
Self::Smallint => i16::try_from(value)
.map(CastValue::Smallint)
.map_err(out_of_range),
Self::Integer => i32::try_from(value)
.map(CastValue::Integer)
.map_err(out_of_range),
Self::Bigint => Ok(CastValue::Bigint(value)),
}
}
}
impl From<IntegerType> for BuiltinType {
fn from(integer: IntegerType) -> Self {
match integer {
IntegerType::Smallint => Self::Smallint,
IntegerType::Integer => Self::Integer,
IntegerType::Bigint => Self::Bigint,
}
}
}
impl TryFrom<BuiltinType> for IntegerType {
type Error = BuiltinType;
fn try_from(pg_type: BuiltinType) -> Result<Self, Self::Error> {
match pg_type {
BuiltinType::Smallint => Ok(Self::Smallint),
BuiltinType::Integer => Ok(Self::Integer),
BuiltinType::Bigint => Ok(Self::Bigint),
other => Err(other),
}
}
}