use serde::{Deserialize, Serialize};
#[cfg(feature = "alloc")]
use crate::to_static::ToStatic;
use crate::types::StringType;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct KeyValue<'a> {
#[serde(borrow)]
pub key: StringType<'a>,
#[serde(borrow)]
pub value: Value<'a>,
}
impl<'a> KeyValue<'a> {
pub fn new<K, V>(key: K, value: V) -> Self
where
K: Into<StringType<'a>>,
V: Into<Value<'a>>,
{
Self {
key: key.into(),
value: value.into(),
}
}
}
#[cfg(feature = "alloc")]
impl ToStatic for KeyValue<'_> {
type Static = KeyValue<'static>;
fn to_static(&self) -> Self::Static {
KeyValue {
key: self.key.clone().into_owned().into(),
value: self.value.to_static(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Value<'a> {
String(#[serde(borrow)] StringType<'a>),
Bool(bool),
I64(i64),
F64(f64),
}
#[cfg(feature = "alloc")]
impl ToStatic for Value<'_> {
type Static = Value<'static>;
fn to_static(&self) -> Self::Static {
match self {
Value::String(s) => Value::String(s.clone().into_owned().into()),
Value::Bool(b) => Value::Bool(*b),
Value::I64(i) => Value::I64(*i),
Value::F64(f) => Value::F64(*f),
}
}
}
#[cfg(feature = "alloc")]
impl<'a> From<alloc::borrow::Cow<'a, str>> for Value<'a> {
fn from(value: alloc::borrow::Cow<'a, str>) -> Self {
Value::String(value)
}
}
#[cfg(feature = "alloc")]
impl<'a> From<alloc::string::String> for Value<'a> {
fn from(value: alloc::string::String) -> Self {
Value::String(value.into())
}
}
#[cfg(feature = "alloc")]
impl<'a> From<&'a alloc::string::String> for Value<'a> {
fn from(value: &'a alloc::string::String) -> Self {
Value::String(value.into())
}
}
impl<'a> From<&'a str> for Value<'a> {
fn from(value: &'a str) -> Self {
#[cfg(feature = "alloc")]
{
Value::String(alloc::borrow::Cow::Borrowed(value))
}
#[cfg(not(feature = "alloc"))]
{
Value::String(value)
}
}
}
impl From<bool> for Value<'_> {
fn from(value: bool) -> Self {
Value::Bool(value)
}
}
impl From<i64> for Value<'_> {
fn from(value: i64) -> Self {
Value::I64(value)
}
}
impl From<f64> for Value<'_> {
fn from(value: f64) -> Self {
Value::F64(value)
}
}