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
use std::fmt;
use locspan_derive::StrippedPartialEq;
#[derive(Clone, Copy, PartialEq, StrippedPartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub enum Nullable<T> {
Null,
Some(T),
}
impl<T> Nullable<T> {
#[inline(always)]
pub fn is_null(&self) -> bool {
matches!(self, Nullable::Null)
}
#[inline(always)]
pub fn is_some(&self) -> bool {
matches!(self, Nullable::Some(_))
}
#[inline(always)]
pub fn unwrap(self) -> T {
match self {
Nullable::Some(t) => t,
Nullable::Null => panic!("cannot unwrap null"),
}
}
#[inline(always)]
pub fn as_ref(&self) -> Nullable<&T> {
match self {
Nullable::Null => Nullable::Null,
Nullable::Some(t) => Nullable::Some(t),
}
}
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),
}
}
#[inline(always)]
pub fn option(self) -> Option<T> {
match self {
Nullable::Null => None,
Nullable::Some(t) => Some(t),
}
}
#[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)),
}
}
pub fn cast<U>(self) -> Nullable<U>
where
T: Into<U>,
{
match self {
Self::Null => Nullable::Null,
Self::Some(t) => Nullable::Some(t.into()),
}
}
pub fn unwrap_or(self, default: T) -> T {
match self {
Self::Null => default,
Self::Some(t) => t,
}
}
pub fn unwrap_or_default(self) -> T
where
T: Default,
{
match self {
Self::Null => T::default(),
Self::Some(t) => t,
}
}
}
impl<'a, T: Clone> Nullable<&'a T> {
#[inline(always)]
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),
}
}
}