1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use std::fmt;
/// Error returned by [`Nullable::try_unwrap`] when the value is `null`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("nullable value was null")]
pub struct NullError;
/// Value that can be `null`.
///
/// `Option` is used throughout this crate for entries that may or may not be
/// present. A JSON-LD entry can also be present with the explicit value
/// `null`, which is meaningful: it unsets whatever the surrounding context
/// inherited. Hence this separate type, so that `Option<Nullable<T>>` can tell
/// an absent entry from an entry set to `null`.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub enum Nullable<T> {
/// The `null` value.
Null,
/// Any other value.
Some(T),
}
impl<T> Nullable<T> {
/// Checks if the value is `null`.
#[inline(always)]
pub fn is_null(&self) -> bool {
matches!(self, Nullable::Null)
}
/// Checks if the value is not `null`.
#[inline(always)]
pub fn is_some(&self) -> bool {
matches!(self, Nullable::Some(_))
}
/// Returns the inner value, or [`NullError`] if `null`.
///
/// # Errors
///
/// Returns an error when the value is null.
#[inline(always)]
pub fn try_unwrap(self) -> Result<T, NullError> {
match self {
Nullable::Some(t) => Ok(t),
Nullable::Null => Err(NullError),
}
}
/// Converts `&Nullable<T>` into `Nullable<&T>`.
#[inline(always)]
pub fn as_ref(&self) -> Nullable<&T> {
match self {
Nullable::Null => Nullable::Null,
Nullable::Some(t) => Nullable::Some(t),
}
}
/// Converts `&Nullable<T>` into `Nullable<&T::Target>` by dereferencing
/// the inner value.
pub fn as_deref(&self) -> Nullable<&T::Target>
where
T: std::ops::Deref,
{
match self {
Self::Null => Nullable::Null,
Self::Some(t) => Nullable::Some(t),
}
}
/// Converts this value into an `Option`, mapping `null` to `None`.
#[inline(always)]
pub fn option(self) -> Option<T> {
match self {
Nullable::Null => None,
Nullable::Some(t) => Some(t),
}
}
/// Maps the inner value with the given function, keeping `null` as `null`.
#[inline(always)]
pub fn map<F, U>(self, f: F) -> Nullable<U>
where
F: FnOnce(T) -> U,
{
match self {
Nullable::Null => Nullable::Null,
Nullable::Some(t) => Nullable::Some(f(t)),
}
}
/// Converts the contained value, keeping null as null.
pub fn cast<U>(self) -> Nullable<U>
where
T: Into<U>,
{
match self {
Self::Null => Nullable::Null,
Self::Some(t) => Nullable::Some(t.into()),
}
}
/// Returns the contained value, or `default` if it is null.
pub fn unwrap_or(self, default: T) -> T {
match self {
Self::Null => default,
Self::Some(t) => t,
}
}
/// Returns the contained value, or the default one if it is null.
pub fn unwrap_or_default(self) -> T
where
T: Default,
{
match self {
Self::Null => T::default(),
Self::Some(t) => t,
}
}
}
impl<T> From<T> for Nullable<T> {
fn from(value: T) -> Self {
Self::Some(value)
}
}
impl<T> From<Option<T>> for Nullable<T> {
fn from(value: Option<T>) -> Self {
match value {
Some(t) => Self::Some(t),
None => Self::Null,
}
}
}
impl<T: Clone> Nullable<&T> {
/// Clones the referenced inner value.
#[inline(always)]
#[must_use]
pub fn cloned(&self) -> Nullable<T> {
match self {
Nullable::Null => Nullable::Null,
Nullable::Some(t) => Nullable::Some((*t).clone()),
}
}
}
impl<T: fmt::Display> fmt::Display for Nullable<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Null => write!(f, "null"),
Self::Some(v) => v.fmt(f),
}
}
}
impl<T: contextual::DisplayWithContext<V>, V> contextual::DisplayWithContext<V> for Nullable<T> {
fn fmt_with(&self, vocabulary: &V, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Null => write!(f, "null"),
Self::Some(v) => v.fmt_with(vocabulary, f),
}
}
}
#[cfg(feature = "serde")]
impl<T: serde::Serialize> serde::Serialize for Nullable<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::Null => serializer.serialize_none(),
Self::Some(t) => serializer.serialize_some(t),
}
}
}
#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for Nullable<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Option::<T>::deserialize(deserializer)?.into())
}
}
#[cfg(feature = "serde")]
impl<T> Nullable<T> {
/// Deserializes a `Nullable<T>` and wraps it in `Some`.
///
/// Meant as the `deserialize_with` of an `Option<Nullable<T>>` field that
/// also carries `#[serde(default)]`: an absent entry then yields `None`,
/// while an entry present with the value `null` yields
/// `Some(Nullable::Null)`. Serde's own handling of `Option` would collapse
/// both cases to `None`.
///
/// # Errors
///
/// Returns the deserializer's error when the value is neither absent, null, nor a valid `T`.
pub fn optional<'de, D>(deserializer: D) -> Result<Option<Self>, D::Error>
where
T: serde::Deserialize<'de>,
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
Ok(Some(Option::<T>::deserialize(deserializer)?.into()))
}
}