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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Provides `DocBuilder` which used to create a `Doc` programmatically.
//!
//! Many of the performance optimizations of `Infograph` are based on the fact
//! that a `Doc` is created once and then never modified. (Of course a new Doc can be created
//! to replace a current version, but the data itself is immutable).
//!
//! Therefore a `DocBuilder` along with the helpers provided here is used to setup the data and
//! then converted into a `Doc` as a final step.
//!
//! Note that there are also helpers like [yaml::hash_to_doc](crate::infograph::yaml::hash_to_doc)
//! or [yaml::list_to_doc](crate::infograph::yaml::list_to_doc) which directly transform a given
//! `Yaml` hash or list into a `Doc`.
use crate::infograph::docs::Doc;
use crate::infograph::node::Node;
use crate::infograph::symbols::{Symbol, SymbolMap, SymbolTable};

/// Provides a builder to generate a `Doc`.
///
/// A doc an internally have either a list or a map as its root node. Therefore either
/// `root_object_builder()`or `root_list_builder()` has to be called the retrieve the
/// appropriate builder after which `build()` must be called to create the resulting `Doc`.
///
/// # Examples
///
/// Creating a list based `Doc`:
/// ```
/// # use jupiter::infograph::builder::DocBuilder;
/// let mut builder = DocBuilder::new();
/// let mut list_builder = builder.root_list_builder();
/// list_builder.append_int(1);
/// list_builder.append_int(2);
/// list_builder.append_int(3);
///
/// let doc = builder.build();
/// assert_eq!(doc.root().at(1).as_int().unwrap(), 2);
/// ```
///
/// Creating a map based `Doc`:
/// ```
/// # use jupiter::infograph::builder::DocBuilder;
/// let mut builder = DocBuilder::new();
/// let mut obj_builder = builder.root_object_builder();
/// obj_builder.put_int("Test", 1);
/// obj_builder.put_int("Foo", 2);
///
/// let doc = builder.build();
/// assert_eq!(doc.root().query("Test").as_int().unwrap(), 1);
/// assert_eq!(doc.root().query("Foo").as_int().unwrap(), 2);
/// ```
pub struct DocBuilder {
    symbols: SymbolTable,
    root: Node,
}

impl DocBuilder {
    /// Creates a new builder instance.
    pub fn new() -> Self {
        DocBuilder {
            symbols: SymbolTable::new(),
            root: Node::Empty,
        }
    }

    /// Resolves the given name into a `Symbol` for repeated insertions.
    ///
    /// # Errors
    /// If the internal symbol table overflows, an error is returned.
    pub fn resolve(&mut self, symbol: impl AsRef<str>) -> anyhow::Result<Symbol> {
        self.symbols.find_or_create(symbol)
    }

    /// Makes the root node of the `Doc` a map and returns a builder for it.
    ///
    /// Note that for each `DocBuilder` either `root_object_builder` or `root_list_builder`
    /// has to called exactly once.  
    pub fn root_object_builder(&mut self) -> ObjectBuilder {
        self.root = Node::Object(SymbolMap::new());
        if let Node::Object(ref mut map) = self.root {
            ObjectBuilder {
                symbols: &mut self.symbols,
                map,
            }
        } else {
            unreachable!("Concurrent modification or corruption a DocBuilder")
        }
    }

    /// Makes the root node of the `Doc` a list and returns a builder for it.
    ///
    /// Note that for each `DocBuilder` either `root_object_builder` or `root_list_builder`
    /// has to called exactly once.  
    pub fn root_list_builder(&mut self) -> ListBuilder {
        self.root = Node::List(Vec::new());

        if let Node::List(ref mut list) = self.root {
            ListBuilder {
                symbols: &mut self.symbols,
                list,
            }
        } else {
            unreachable!("Concurrent modification or corruption a DocBuilder")
        }
    }

    /// Turns the builder into a `Doc`.
    pub fn build(self) -> Doc {
        Doc::new(self.symbols, self.root)
    }
}

/// Builds an inner object or map within a `Doc` or another element.
///
/// A builder can either be obtained via [DocBuilder::root_object_builder](DocBuilder::root_object_builder)
/// or using either [ObjectBuilder::put_object](ObjectBuilder::put_object) - to place an inner
/// object in another or via [ListBuilder::append_object](ListBuilder::append_object) to add an
/// object to a list.
pub struct ObjectBuilder<'a> {
    symbols: &'a mut SymbolTable,
    map: &'a mut SymbolMap<Node>,
}

impl<'a> ObjectBuilder<'a> {
    /// Places an integer value within the object being built.
    ///
    /// # Errors
    /// If the internal symbol table overflows, an error is returned.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// obj_builder.put_int("Test", 42).unwrap();
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").as_int().unwrap(), 42);
    /// ```
    pub fn put_int(&mut self, key: impl AsRef<str>, value: i64) -> anyhow::Result<()> {
        let symbol = self.symbols.find_or_create(key)?;
        self.insert_int(symbol, value);
        Ok(())
    }

    /// Places an integer value within the object being built using a `Symbol`which has been looked
    /// up previously.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let key = builder.resolve("Test").unwrap();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// obj_builder.insert_int(key, 42);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").as_int().unwrap(), 42);
    /// ```
    pub fn insert_int(&mut self, key: Symbol, value: i64) {
        self.map.put(key, Node::Integer(value));
    }

    /// Places a string value within the object being built.
    ///
    /// # Errors
    /// If the internal symbol table overflows, an error is returned.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// obj_builder.put_string("Test", "Foo").unwrap();
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").as_str().unwrap(), "Foo");
    /// ```
    pub fn put_string(
        &mut self,
        key: impl AsRef<str>,
        value: impl AsRef<str>,
    ) -> anyhow::Result<()> {
        let symbol = self.symbols.find_or_create(key)?;
        self.insert_string(symbol, value);

        Ok(())
    }

    /// Places a string value within the object being built using a `Symbol`which has been looked
    /// up previously.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let key = builder.resolve("Test").unwrap();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// obj_builder.insert_string(key, "Foo");
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").as_str().unwrap(), "Foo");
    /// ```
    pub fn insert_string(&mut self, key: Symbol, value: impl AsRef<str>) {
        self.map.put(key, Node::from(value.as_ref()));
    }

    /// Places a bool value within the object being built.
    ///
    /// # Errors
    /// If the internal symbol table overflows, an error is returned.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// obj_builder.put_bool("Test", true).unwrap();
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").as_bool(), true);
    /// ```
    pub fn put_bool(&mut self, key: impl AsRef<str>, value: bool) -> anyhow::Result<()> {
        let symbol = self.symbols.find_or_create(key)?;
        self.insert_bool(symbol, value);

        Ok(())
    }

    /// Places bool value within the object being built using a `Symbol`which has been looked
    /// up previously.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let key = builder.resolve("Test").unwrap();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// obj_builder.insert_bool(key, true);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").as_bool(), true);
    /// ```
    pub fn insert_bool(&mut self, key: Symbol, value: bool) {
        self.map.put(key, Node::Boolean(value));
    }

    /// Places a list value within the object being built. Returns the builder used to populate
    /// the list.
    ///
    /// # Errors
    /// If the internal symbol table overflows, an error is returned.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// let mut list_builder = obj_builder.put_list("Test").unwrap();
    /// list_builder.append_int(1);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").at(0).as_int().unwrap(), 1);
    /// ```
    pub fn put_list(&mut self, key: impl AsRef<str>) -> anyhow::Result<ListBuilder> {
        let symbol = self.symbols.find_or_create(key)?;
        Ok(self.insert_list(symbol))
    }

    /// Places a list value within the object being built using a `Symbol`which has been looked
    /// up previously. Returns the builder used to populate the list.   
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let key = builder.resolve("Test").unwrap();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// let mut list_builder = obj_builder.insert_list(key);
    /// list_builder.append_int(1);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test").at(0).as_int().unwrap(), 1);
    /// ```
    pub fn insert_list(&mut self, key: Symbol) -> ListBuilder {
        self.map.put(key, Node::List(Vec::new()));
        if let Node::List(ref mut list) = self.map.get_mut(key).unwrap() {
            ListBuilder {
                symbols: self.symbols,
                list,
            }
        } else {
            unreachable!("Concurrent modification or corruption of the underlying map!")
        }
    }

    /// Places an inner object within the object being built. Returns the builder used to populate
    /// the list.
    ///
    /// # Errors
    /// If the internal symbol table overflows, an error is returned.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// let mut inner_obj_builder = obj_builder.put_object("Test").unwrap();
    /// inner_obj_builder.put_string("Foo", "Bar").unwrap();
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test.Foo").as_str().unwrap(), "Bar");
    /// ```
    pub fn put_object(&mut self, key: impl AsRef<str>) -> anyhow::Result<ObjectBuilder> {
        let symbol = self.symbols.find_or_create(key)?;
        Ok(self.insert_object(symbol))
    }

    /// Places an inner object within the object being built using a `Symbol`which has been looked
    /// up previously. Returns the builder used to populate the list.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let key = builder.resolve("Test").unwrap();
    /// let mut obj_builder = builder.root_object_builder();
    ///
    /// let mut inner_obj_builder = obj_builder.insert_object(key);
    /// inner_obj_builder.put_string("Foo", "Bar").unwrap();
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().query("Test.Foo").as_str().unwrap(), "Bar");
    /// ```
    pub fn insert_object(&mut self, key: Symbol) -> ObjectBuilder {
        self.map.put(key, Node::Object(SymbolMap::new()));
        if let Node::Object(ref mut map) = self.map.get_mut(key).unwrap() {
            ObjectBuilder {
                symbols: self.symbols,
                map,
            }
        } else {
            unreachable!("Concurrent modification or corruption of the underlying map!")
        }
    }
}

/// Builds an inner list within a `Doc` or another element.
///
/// A builder can either be obtained via [DocBuilder::root_list_builder](DocBuilder::root_list_builder)
/// or using either [ObjectBuilder::put_list](ObjectBuilder::put_list) - to place an inner
/// list in another or via [ListBuilder::append_list](ListBuilder::append_list) to add a
/// list as child element to a list.
pub struct ListBuilder<'a> {
    symbols: &'a mut SymbolTable,
    list: &'a mut Vec<Node>,
}

impl<'a> ListBuilder<'a> {
    /// Appends an integer value to the list being built.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut list_builder = builder.root_list_builder();
    ///
    /// list_builder.append_int(42);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().at(0).as_int().unwrap(), 42);
    /// ```
    pub fn append_int(&mut self, value: i64) {
        self.list.push(Node::Integer(value));
    }

    /// Appends a string to the list being built.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut list_builder = builder.root_list_builder();
    ///
    /// list_builder.append_string("Test");
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().at(0).as_str().unwrap(), "Test");
    /// ```
    pub fn append_string(&mut self, value: impl AsRef<str>) {
        self.list.push(Node::from(value.as_ref()));
    }

    /// Appends a bool value to the list being built.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut list_builder = builder.root_list_builder();
    ///
    /// list_builder.append_bool(true);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().at(0).as_bool(), true);    
    /// ```
    pub fn append_bool(&mut self, value: bool) {
        self.list.push(Node::Boolean(value));
    }

    /// Appends a child-list to the list being built. Returns the builder used to populate the list.
    ///
    /// Note that this will not join two lists but rather construct a list as child element and
    /// append further items to this child list.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut list_builder = builder.root_list_builder();
    ///
    /// let mut child_list_builder = list_builder.append_list();
    /// child_list_builder.append_int(42);
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().len(), 1);    
    /// assert_eq!(doc.root().at(0).len(), 1);    
    /// assert_eq!(doc.root().at(0).at(0).as_int().unwrap(), 42);
    /// ```
    pub fn append_list(&mut self) -> ListBuilder {
        self.list.push(Node::List(Vec::new()));
        if let Node::List(ref mut list) = self.list.last_mut().unwrap() {
            ListBuilder {
                symbols: self.symbols,
                list,
            }
        } else {
            unreachable!("Concurrent modification or corruption of the underlying list!")
        }
    }

    /// Appends a child object to the list being built. Returns the builder used to populate the
    /// object.
    ///
    /// # Example
    /// ```
    /// # use jupiter::infograph::builder::DocBuilder;
    /// let mut builder = DocBuilder::new();
    /// let mut list_builder = builder.root_list_builder();
    ///
    /// let mut obj_builder = list_builder.append_object();
    /// obj_builder.put_string("Foo", "Bar").unwrap();
    ///
    /// let doc = builder.build();
    /// assert_eq!(doc.root().len(), 1);    
    /// assert_eq!(doc.root().at(0).query("Foo").as_str().unwrap(), "Bar");
    /// ```
    pub fn append_object(&mut self) -> ObjectBuilder {
        self.list.push(Node::Object(SymbolMap::new()));
        if let Node::Object(ref mut map) = self.list.last_mut().unwrap() {
            ObjectBuilder {
                symbols: self.symbols,
                map,
            }
        } else {
            unreachable!("Concurrent modification or corruption of the underlying list!")
        }
    }
}