use std::{borrow::Cow, ops::Deref};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{registry, InputType, InputValueError, InputValueResult, Value};
#[allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum MaybeUndefined<T> {
Undefined,
Null,
Value(T),
}
impl<T> Default for MaybeUndefined<T> {
fn default() -> Self {
Self::Undefined
}
}
impl<T> MaybeUndefined<T> {
#[inline]
pub const fn is_undefined(&self) -> bool {
matches!(self, MaybeUndefined::Undefined)
}
#[inline]
pub const fn is_null(&self) -> bool {
matches!(self, MaybeUndefined::Null)
}
#[inline]
pub const fn is_value(&self) -> bool {
matches!(self, MaybeUndefined::Value(_))
}
#[inline]
pub const fn value(&self) -> Option<&T> {
match self {
MaybeUndefined::Value(value) => Some(value),
_ => None,
}
}
#[inline]
pub fn take(self) -> Option<T> {
match self {
MaybeUndefined::Value(value) => Some(value),
_ => None,
}
}
#[inline]
pub const fn as_opt_ref(&self) -> Option<Option<&T>> {
match self {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(None),
MaybeUndefined::Value(value) => Some(Some(value)),
}
}
#[inline]
pub fn as_opt_deref<U>(&self) -> Option<Option<&U>>
where
U: ?Sized,
T: Deref<Target = U>,
{
match self {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(None),
MaybeUndefined::Value(value) => Some(Some(value.deref())),
}
}
#[inline]
pub fn contains_value<U>(&self, x: &U) -> bool
where
U: PartialEq<T>,
{
match self {
MaybeUndefined::Value(y) => x == y,
_ => false,
}
}
#[inline]
pub fn contains<U>(&self, x: &Option<U>) -> bool
where
U: PartialEq<T>,
{
match self {
MaybeUndefined::Value(y) => matches!(x, Some(v) if v == y),
MaybeUndefined::Null => x.is_none(),
MaybeUndefined::Undefined => false,
}
}
#[inline]
pub fn map<U, F: FnOnce(Option<T>) -> Option<U>>(self, f: F) -> MaybeUndefined<U> {
match self {
MaybeUndefined::Value(v) => match f(Some(v)) {
Some(v) => MaybeUndefined::Value(v),
None => MaybeUndefined::Null,
},
MaybeUndefined::Null => match f(None) {
Some(v) => MaybeUndefined::Value(v),
None => MaybeUndefined::Null,
},
MaybeUndefined::Undefined => MaybeUndefined::Undefined,
}
}
#[inline]
pub fn map_value<U, F: FnOnce(T) -> U>(self, f: F) -> MaybeUndefined<U> {
match self {
MaybeUndefined::Value(v) => MaybeUndefined::Value(f(v)),
MaybeUndefined::Null => MaybeUndefined::Null,
MaybeUndefined::Undefined => MaybeUndefined::Undefined,
}
}
pub fn update_to(self, value: &mut Option<T>) {
match self {
MaybeUndefined::Value(new) => *value = Some(new),
MaybeUndefined::Null => *value = None,
MaybeUndefined::Undefined => {}
};
}
}
impl<T: InputType> InputType for MaybeUndefined<T> {
type RawValueType = T::RawValueType;
fn type_name() -> Cow<'static, str> {
T::type_name()
}
fn qualified_type_name() -> String {
T::type_name().to_string()
}
fn create_type_info(registry: &mut registry::Registry) -> String {
T::create_type_info(registry);
T::type_name().to_string()
}
fn parse(value: Option<Value>) -> InputValueResult<Self> {
match value {
None => Ok(MaybeUndefined::Undefined),
Some(Value::Null) => Ok(MaybeUndefined::Null),
Some(value) => Ok(MaybeUndefined::Value(
T::parse(Some(value)).map_err(InputValueError::propagate)?,
)),
}
}
fn to_value(&self) -> Value {
match self {
MaybeUndefined::Value(value) => value.to_value(),
_ => Value::Null,
}
}
fn as_raw_value(&self) -> Option<&Self::RawValueType> {
if let MaybeUndefined::Value(value) = self {
value.as_raw_value()
} else {
None
}
}
}
impl<T, E> MaybeUndefined<Result<T, E>> {
#[inline]
pub fn transpose(self) -> Result<MaybeUndefined<T>, E> {
match self {
MaybeUndefined::Undefined => Ok(MaybeUndefined::Undefined),
MaybeUndefined::Null => Ok(MaybeUndefined::Null),
MaybeUndefined::Value(Ok(v)) => Ok(MaybeUndefined::Value(v)),
MaybeUndefined::Value(Err(e)) => Err(e),
}
}
}
impl<T: Serialize> Serialize for MaybeUndefined<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
MaybeUndefined::Value(value) => value.serialize(serializer),
_ => serializer.serialize_none(),
}
}
}
impl<'de, T> Deserialize<'de> for MaybeUndefined<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<MaybeUndefined<T>, D::Error>
where
D: Deserializer<'de>,
{
Option::<T>::deserialize(deserializer).map(|value| match value {
Some(value) => MaybeUndefined::Value(value),
None => MaybeUndefined::Null,
})
}
}
impl<T> From<MaybeUndefined<T>> for Option<Option<T>> {
fn from(maybe_undefined: MaybeUndefined<T>) -> Self {
match maybe_undefined {
MaybeUndefined::Undefined => None,
MaybeUndefined::Null => Some(None),
MaybeUndefined::Value(value) => Some(Some(value)),
}
}
}
impl<T> From<Option<Option<T>>> for MaybeUndefined<T> {
fn from(value: Option<Option<T>>) -> Self {
match value {
Some(Some(value)) => Self::Value(value),
Some(None) => Self::Null,
None => Self::Undefined,
}
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use crate::*;
#[test]
fn test_maybe_undefined_type() {
assert_eq!(MaybeUndefined::<i32>::type_name(), "Int");
assert_eq!(MaybeUndefined::<i32>::qualified_type_name(), "Int");
assert_eq!(&MaybeUndefined::<i32>::type_name(), "Int");
assert_eq!(&MaybeUndefined::<i32>::qualified_type_name(), "Int");
}
#[test]
fn test_maybe_undefined_serde() {
assert_eq!(
to_value(MaybeUndefined::Value(100i32)).unwrap(),
value!(100)
);
assert_eq!(
from_value::<MaybeUndefined<i32>>(value!(100)).unwrap(),
MaybeUndefined::Value(100)
);
assert_eq!(
from_value::<MaybeUndefined<i32>>(value!(null)).unwrap(),
MaybeUndefined::Null
);
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
struct A {
a: MaybeUndefined<i32>,
}
assert_eq!(
to_value(&A {
a: MaybeUndefined::Value(100i32)
})
.unwrap(),
value!({"a": 100})
);
assert_eq!(
to_value(&A {
a: MaybeUndefined::Null,
})
.unwrap(),
value!({ "a": null })
);
assert_eq!(
to_value(&A {
a: MaybeUndefined::Undefined,
})
.unwrap(),
value!({ "a": null })
);
assert_eq!(
from_value::<A>(value!({"a": 100})).unwrap(),
A {
a: MaybeUndefined::Value(100i32)
}
);
assert_eq!(
from_value::<A>(value!({ "a": null })).unwrap(),
A {
a: MaybeUndefined::Null
}
);
assert_eq!(
from_value::<A>(value!({})).unwrap(),
A {
a: MaybeUndefined::Null
}
);
}
#[test]
fn test_maybe_undefined_to_nested_option() {
assert_eq!(Option::<Option<i32>>::from(MaybeUndefined::Undefined), None);
assert_eq!(
Option::<Option<i32>>::from(MaybeUndefined::Null),
Some(None)
);
assert_eq!(
Option::<Option<i32>>::from(MaybeUndefined::Value(42)),
Some(Some(42))
);
}
#[test]
fn test_as_opt_ref() {
let value = MaybeUndefined::<String>::Undefined;
let r = value.as_opt_ref();
assert_eq!(r, None);
let value = MaybeUndefined::<String>::Null;
let r = value.as_opt_ref();
assert_eq!(r, Some(None));
let value = MaybeUndefined::<String>::Value("abc".to_string());
let r = value.as_opt_ref();
assert_eq!(r, Some(Some(&"abc".to_string())));
}
#[test]
fn test_as_opt_deref() {
let value = MaybeUndefined::<String>::Undefined;
let r = value.as_opt_deref();
assert_eq!(r, None);
let value = MaybeUndefined::<String>::Null;
let r = value.as_opt_deref();
assert_eq!(r, Some(None));
let value = MaybeUndefined::<String>::Value("abc".to_string());
let r = value.as_opt_deref();
assert_eq!(r, Some(Some("abc")));
}
#[test]
fn test_contains_value() {
let test = "abc";
let mut value: MaybeUndefined<String> = MaybeUndefined::Undefined;
assert!(!value.contains_value(&test));
value = MaybeUndefined::Null;
assert!(!value.contains_value(&test));
value = MaybeUndefined::Value("abc".to_string());
assert!(value.contains_value(&test));
}
#[test]
fn test_contains() {
let test = Some("abc");
let none: Option<&str> = None;
let mut value: MaybeUndefined<String> = MaybeUndefined::Undefined;
assert!(!value.contains(&test));
assert!(!value.contains(&none));
value = MaybeUndefined::Null;
assert!(!value.contains(&test));
assert!(value.contains(&none));
value = MaybeUndefined::Value("abc".to_string());
assert!(value.contains(&test));
assert!(!value.contains(&none));
}
#[test]
fn test_map_value() {
let mut value: MaybeUndefined<i32> = MaybeUndefined::Undefined;
assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Undefined);
value = MaybeUndefined::Null;
assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Null);
value = MaybeUndefined::Value(5);
assert_eq!(value.map_value(|v| v > 2), MaybeUndefined::Value(true));
}
#[test]
fn test_map() {
let mut value: MaybeUndefined<i32> = MaybeUndefined::Undefined;
assert_eq!(value.map(|v| Some(v.is_some())), MaybeUndefined::Undefined);
value = MaybeUndefined::Null;
assert_eq!(
value.map(|v| Some(v.is_some())),
MaybeUndefined::Value(false)
);
value = MaybeUndefined::Value(5);
assert_eq!(
value.map(|v| Some(v.is_some())),
MaybeUndefined::Value(true)
);
}
#[test]
fn test_transpose() {
let mut value: MaybeUndefined<Result<i32, &'static str>> = MaybeUndefined::Undefined;
assert_eq!(value.transpose(), Ok(MaybeUndefined::Undefined));
value = MaybeUndefined::Null;
assert_eq!(value.transpose(), Ok(MaybeUndefined::Null));
value = MaybeUndefined::Value(Ok(5));
assert_eq!(value.transpose(), Ok(MaybeUndefined::Value(5)));
value = MaybeUndefined::Value(Err("error"));
assert_eq!(value.transpose(), Err("error"));
}
}