use std::collections::{BTreeMap, HashMap};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
use uuid::Uuid;
use super::Value;
#[derive(Clone, Debug, PartialEq)]
pub struct Param(pub(super) Value);
impl Param {
pub fn null() -> Self {
Param(Value::Null)
}
pub fn value(&self) -> &Value {
&self.0
}
}
impl From<Value> for Param {
fn from(v: Value) -> Self {
Param(v)
}
}
pub trait ArrayElement: Into<Param> {}
macro_rules! scalar {
($($ty:ty => |$v:ident| $make:expr),* $(,)?) => {
$(
impl From<$ty> for Param {
fn from($v: $ty) -> Self {
Param($make)
}
}
)*
};
}
scalar! {
u8 => |v| Value::UInt(v.into()),
u16 => |v| Value::UInt(v.into()),
u32 => |v| Value::UInt(v.into()),
u64 => |v| Value::UInt(v),
usize => |v| Value::UInt(v as u64),
i8 => |v| Value::Int(v.into()),
i16 => |v| Value::Int(v.into()),
i32 => |v| Value::Int(v.into()),
i64 => |v| Value::Int(v),
isize => |v| Value::Int(v as i64),
i128 => |v| Value::Int128(v),
u128 => |v| Value::UInt128(v),
f32 => |v| Value::Float32(v),
f64 => |v| Value::Float64(v),
bool => |v| Value::Bool(v),
&str => |v| Value::from(v),
String => |v| Value::from(v),
&String => |v| Value::from(v.as_str()),
Vec<u8> => |v| Value::String(v),
&[u8] => |v| Value::String(v.to_vec()),
Uuid => |v| Value::Uuid(v),
DateTime<Utc> => |v| Value::from(v),
NaiveDateTime => |v| Value::from(v.and_utc()),
NaiveDate => |v| Value::date(v),
Ipv4Addr => |v| Value::Ipv4(v),
Ipv6Addr => |v| Value::Ipv6(v),
IpAddr => |v| match v {
IpAddr::V4(ip) => Value::Ipv4(ip),
IpAddr::V6(ip) => Value::Ipv6(ip),
},
}
macro_rules! element {
($($ty:ty),* $(,)?) => {
$(impl ArrayElement for $ty {})*
};
}
element!(
u16,
u32,
u64,
usize,
i8,
i16,
i32,
i64,
isize,
i128,
u128,
f32,
f64,
bool,
&str,
String,
&String,
Vec<u8>,
&[u8],
Uuid,
DateTime<Utc>,
NaiveDateTime,
NaiveDate,
Ipv4Addr,
Ipv6Addr,
IpAddr,
Value,
Param,
);
impl<T: Into<Param>> ArrayElement for Option<T> {}
impl<T: ArrayElement> ArrayElement for Vec<T> {}
impl<K: Into<Param>, V: Into<Param>, S> ArrayElement for HashMap<K, V, S> {}
impl<K: Into<Param>, V: Into<Param>> ArrayElement for BTreeMap<K, V> {}
impl<T: Into<Param>> From<Option<T>> for Param {
fn from(v: Option<T>) -> Self {
v.map_or(Param(Value::Null), Into::into)
}
}
impl<T: ArrayElement> From<Vec<T>> for Param {
fn from(v: Vec<T>) -> Self {
Param(Value::Array(v.into_iter().map(|e| e.into().0).collect()))
}
}
impl<K: Into<Param>, V: Into<Param>, S> From<HashMap<K, V, S>> for Param {
fn from(m: HashMap<K, V, S>) -> Self {
Param(Value::Map(
m.into_iter()
.map(|(k, v)| (k.into().0, v.into().0))
.collect(),
))
}
}
impl<K: Into<Param>, V: Into<Param>> From<BTreeMap<K, V>> for Param {
fn from(m: BTreeMap<K, V>) -> Self {
Param(Value::Map(
m.into_iter()
.map(|(k, v)| (k.into().0, v.into().0))
.collect(),
))
}
}