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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use super::super::{
super::{annotate::*, kv::*, path::*},
blob::*,
boolean::*,
depict::*,
float::*,
integer::*,
iterator::*,
list::*,
map::*,
null::*,
text::*,
unsigned_integer::*,
};
use {kutil::std::immutable::*, std::mem::*};
//
// Variant
//
/// Container for normal types.
#[derive(Clone, Debug, Default)]
pub enum Variant<AnnotatedT> {
/// Undefined. This is different from [Null]!
#[default]
Undefined,
/// Null. This is different from [Undefined](Variant::Undefined)!
Null(Null<AnnotatedT>),
/// Integer.
Integer(Integer<AnnotatedT>),
/// Unsigned integer.
UnsignedInteger(UnsignedInteger<AnnotatedT>),
/// Float.
Float(Float<AnnotatedT>),
/// Boolean.
Boolean(Boolean<AnnotatedT>),
/// Text.
Text(Text<AnnotatedT>),
/// Blob.
Blob(Blob<AnnotatedT>),
/// List.
List(List<AnnotatedT>),
/// Map.
Map(Map<AnnotatedT>),
}
impl<AnnotatedT> Variant<AnnotatedT> {
/// The variant's type name.
pub fn type_name(&self) -> &'static str {
match self {
Self::Undefined => "Undefined",
Self::Null(_) => "Null",
Self::Integer(_) => "Integer",
Self::UnsignedInteger(_) => "UnsignedInteger",
Self::Float(_) => "Float",
Self::Boolean(_) => "Boolean",
Self::Text(_) => "Text",
Self::Blob(_) => "Blob",
Self::List(_) => "List",
Self::Map(_) => "Map",
}
}
/// Compare type.
pub fn same_type(&self, other: &Self) -> bool {
discriminant(self) == discriminant(other)
}
/// True if [Undefined](Variant::Undefined).
pub fn is_undefined(&self) -> bool {
matches!(self, Self::Undefined)
}
/// True if [Null].
pub fn is_null(&self) -> bool {
matches!(self, Self::Null(_))
}
/// True if [List] or [Map].
pub fn is_collection(&self) -> bool {
matches!(self, Self::List(_) | Self::Map(_))
}
/// Gets a reference to a nested variant.
///
/// If this is a [Map], the argument is treated as a key.
///
/// If this is a [List], the argument is treated as an index and must be an
/// [Variant::UnsignedInteger] or an [Variant::Integer].
pub fn get(&self, key: &Self) -> Option<&Self> {
match (self, key) {
(Self::Map(map), key) => map.inner.get(key),
(Self::List(list), Self::UnsignedInteger(unsigned_integer)) => {
list.inner.get(unsigned_integer.inner as usize)
}
(Self::List(list), Self::Integer(integer)) => list.inner.get(integer.inner as usize),
_ => None,
}
}
/// Gets a mutable reference to a nested variant.
///
/// If this is a [Map], the argument is treated as a key.
///
/// If this is a [List], the argument is treated as an index and must be an [UnsignedInteger]
/// or an [Integer].
pub fn get_mut(&mut self, key: &Self) -> Option<&mut Self> {
match (self, key) {
(Self::Map(map), key) => map.inner.get_mut(key),
(Self::List(list), Self::UnsignedInteger(unsigned_integer)) => {
list.inner.get_mut(unsigned_integer.inner as usize)
}
(Self::List(list), Self::Integer(integer)) => list.inner.get_mut(integer.inner as usize),
_ => None,
}
}
/// Removes a reference to a nested variant.
///
/// If this is a [Map], the argument is treated as a key.
///
/// If this is a [List], the argument is treated as an index and must be an
/// [Variant::UnsignedInteger] or an [Variant::Integer].
pub fn remove(&mut self, key: &Self) -> Option<Self> {
match (self, key) {
(Self::Map(map), key) => map.inner.remove(key),
(Self::List(list), Self::UnsignedInteger(unsigned_integer)) => list.remove(unsigned_integer.inner as usize),
(Self::List(list), Self::Integer(integer)) => list.remove(integer.inner as usize),
_ => None,
}
}
/// Gets a reference to a nested variant.
///
/// If this is a [Map], the argument is treated as a key.
///
/// If this is a [List], the argument is treated as an index and must be an [UnsignedInteger]
/// or an [Integer].
pub fn into_get<KeyT>(&self, key: KeyT) -> Option<&Self>
where
KeyT: Into<Self>,
{
self.get(&key.into())
}
/// Gets a mutable reference to a nested variant.
///
/// If this is a [Map], the argument is treated as a key.
///
/// If this is a [List], the argument is treated as an index and must be an [UnsignedInteger]
/// or an [Integer].
pub fn into_get_mut<KeyT>(&mut self, key: KeyT) -> Option<&mut Self>
where
KeyT: Into<Self>,
{
self.get_mut(&key.into())
}
/// Removes a reference to a nested variant.
///
/// If this is a [Map], the argument is treated as a key.
///
/// If this is a [List], the argument is treated as an index and must be an
/// [Variant::UnsignedInteger] or an [Variant::Integer].
pub fn into_remove<KeyT>(&mut self, key: KeyT) -> Option<Self>
where
KeyT: Into<Self>,
{
self.remove(&key.into())
}
/// Traverse the variant by calling [Variant::get] repeatedly.
///
/// Any non-collection or missing key will cause the traversal to stop and return [None].
///
/// Use the [traverse!](crate::traverse) macro instead if you can. It will generally
/// be more efficient because it doesn't require an allocated iterator.
pub fn traverse<'own, IteratorT>(&self, keys: IteratorT) -> Option<&Self>
where
AnnotatedT: 'own,
IteratorT: Iterator<Item = &'own Self>,
{
let mut found = self;
for key in keys {
found = found.get(key)?;
}
Some(found)
}
/// Traverse the variant by calling [Variant::get_mut] repeatedly.
///
/// Any non-collection or missing key will cause the traversal to stop and return [None].
///
/// Use the [traverse_mut!](crate::traverse_mut) macro instead if you can. It will generally
/// be more efficient because it doesn't require an allocated iterator.
pub fn traverse_mut<'own, IteratorT>(&mut self, keys: IteratorT) -> Option<&mut Self>
where
AnnotatedT: 'own,
IteratorT: Iterator<Item = &'own Self>,
{
let mut found = self;
for key in keys {
found = found.get_mut(key)?;
}
Some(found)
}
/// If the variant is a [List] with length of 2, returns it as a tuple.
///
/// Useful when using the list as a key-value pair for a map.
pub fn to_pair(&self) -> Option<(&Self, &Self)> {
match self {
Self::List(list) => list.to_pair(),
_ => None,
}
}
/// If the variant is a [List] with length of 2, returns it as a tuple.
///
/// Useful when using the list as a key-value pair for a map.
pub fn into_pair(self) -> Option<(Self, Self)> {
match self {
Self::List(list) => list.into_pair(),
_ => None,
}
}
/// If the variant is a [Map] with *only* one key, returns the key-value tuple.
pub fn to_key_value_pair(&self) -> Option<(&Self, &Self)> {
match self {
Self::Map(map) => map.to_key_value_pair(),
_ => None,
}
}
/// If the variant is a [Map] with *only* one key, returns the key-value tuple.
pub fn into_key_value_pair(self) -> Option<(Self, Self)> {
match self {
Self::Map(map) => map.into_key_value_pair(),
_ => None,
}
}
/// If the variant is a [List], iterates its items. Otherwise just iterates itself once.
pub fn iterator(&self) -> VariantIterator<'_, AnnotatedT> {
VariantIterator::new(self)
}
/// If the variant is a [List], iterates its items. Otherwise just iterates itself once.
pub fn into_iterator(self) -> IntoVariantIterator<AnnotatedT> {
IntoVariantIterator::new(self)
}
/// An iterator for key-value pairs.
///
/// Can be used on a [Map] or a [List]. The items in a [List] are expected to each be key-value
/// pairs ([List] of length 2) with unique keys.
///
/// Note that the iterator is a `dyn` in order to support different underlying implementations.
pub fn into_key_value_iterator<'own>(self) -> Option<Box<dyn IntoKeyValuePairIterator<AnnotatedT> + 'own>>
where
AnnotatedT: 'own + Clone + Default,
{
match self {
Self::Map(map) => Some(Box::new(IntoKeyValuePairIteratorForBTreeMap::new_for(map.inner))),
Self::List(list) => Some(Box::new(IntoKeyValuePairIteratorForVariantIterator::new_for(list))),
_ => None,
}
}
/// An iterator for key-value pairs.
///
/// Can be used on a [Map] or a [List]. The items in a [List] are expected to each be key-value
/// pairs ([List] of length 2) with unique keys.
///
/// Note that the iterator is a `dyn` in order to support different underlying implementations.
pub fn key_value_iterator<'own>(&'own self) -> Option<Box<dyn KeyValuePairIterator<AnnotatedT> + 'own>>
where
AnnotatedT: Default,
{
match self {
Self::Map(map) => Some(Box::new(KeyValuePairIteratorForBTreeMap::new_for(&map.inner))),
Self::List(list) => Some(Box::new(KeyValuePairIteratorForVariantIterator::new_for(list))),
_ => None,
}
}
/// Add source and [PathRepresentation] to all [Annotations] recursively.
pub fn fully_annotated(mut self, source: &Option<ByteString>) -> Self
where
AnnotatedT: Annotated + Default,
{
if AnnotatedT::can_have_annotations() {
let path = self.annotations().and_then(|annotations| annotations.path.clone()).unwrap_or_default();
self.fully_annotate(source, &path);
}
self
}
fn fully_annotate(&mut self, source: &Option<ByteString>, base_path: &PathRepresentation)
where
AnnotatedT: Annotated + Default,
{
if source.is_some() {
if let Some(annotations) = self.annotations_mut() {
annotations.source = source.clone();
}
}
match self {
Self::List(list) => {
for (index, value) in list.inner.iter_mut().enumerate() {
let mut path = base_path.clone();
path.push_list_index(index);
value.fully_annotate(source, &path);
if let Some(annotations) = value.annotations_mut() {
annotations.path = Some(path);
}
}
}
Self::Map(map) => {
let mut vector = map.into_vector();
for (key, value) in vector.iter_mut() {
let mut path = base_path.clone();
path.push_map_key(key.to_string().into());
key.fully_annotate(source, &path);
value.fully_annotate(source, &path);
if let Some(annotations) = key.annotations_mut() {
annotations.path = Some(path.clone());
}
if let Some(annotations) = value.annotations_mut() {
annotations.path = Some(path);
}
}
*map = Map::from_iter(vector).with_annotations_from(map);
}
_ => {}
}
}
/// [Depict](depiction::Depict) with [Annotations].
pub fn annotated_depict(&self) -> AnnotatedDepictVariant<'_, AnnotatedT> {
AnnotatedDepictVariant::new(self, AnnotatedDepictionMode::Inline)
}
}