#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Null,
Bool(bool),
I32(i32),
I64(i64),
F32(f32),
F64(f64),
Text(String),
Bytes(Vec<u8>),
#[cfg(feature = "uuid")]
Uuid(uuid::Uuid),
#[cfg(feature = "json")]
Json(serde_json::Value),
#[cfg(feature = "chrono")]
Timestamp(chrono::DateTime<chrono::Utc>),
}
impl From<bool> for Value {
fn from(v: bool) -> Self {
Self::Bool(v)
}
}
impl From<i32> for Value {
fn from(v: i32) -> Self {
Self::I32(v)
}
}
impl From<i64> for Value {
fn from(v: i64) -> Self {
Self::I64(v)
}
}
impl From<f32> for Value {
fn from(v: f32) -> Self {
Self::F32(v)
}
}
impl From<f64> for Value {
fn from(v: f64) -> Self {
Self::F64(v)
}
}
impl From<String> for Value {
fn from(v: String) -> Self {
Self::Text(v)
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Self::Text(v.to_owned())
}
}
impl From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Self {
Self::Bytes(v)
}
}
#[cfg(feature = "uuid")]
impl From<uuid::Uuid> for Value {
fn from(v: uuid::Uuid) -> Self {
Self::Uuid(v)
}
}
#[cfg(feature = "json")]
impl From<serde_json::Value> for Value {
fn from(v: serde_json::Value) -> Self {
Self::Json(v)
}
}
#[cfg(feature = "chrono")]
impl From<chrono::DateTime<chrono::Utc>> for Value {
fn from(v: chrono::DateTime<chrono::Utc>) -> Self {
Self::Timestamp(v)
}
}
impl<T: Into<Self>> From<Option<T>> for Value {
fn from(v: Option<T>) -> Self {
match v {
Some(v) => v.into(),
None => Self::Null,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bool_from_impl() {
assert_eq!(Value::from(true), Value::Bool(true));
}
#[cfg(feature = "uuid")]
#[test]
fn uuid_from_impl() {
let id = uuid::Uuid::nil();
assert_eq!(Value::from(id), Value::Uuid(id));
}
#[cfg(feature = "json")]
#[test]
fn json_from_impl() {
let v = serde_json::json!({"key": "value"});
assert_eq!(Value::from(v.clone()), Value::Json(v));
}
#[cfg(feature = "chrono")]
#[test]
fn timestamp_from_impl() {
let ts = chrono::Utc::now();
assert_eq!(Value::from(ts), Value::Timestamp(ts));
}
}