forked from biojppm/rapidyaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickstart.cpp
5328 lines (4920 loc) · 214 KB
/
quickstart.cpp
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ryml: quickstart
//-----------------------------------------------------------------------------
// ryml can be used as a single header, or as a simple library:
#if defined(RYML_SINGLE_HEADER) // using the single header directly in the executable
#define RYML_SINGLE_HDR_DEFINE_NOW
#include <ryml_all.hpp>
#elif defined(RYML_SINGLE_HEADER_LIB) // using the single header from a library
#include <ryml_all.hpp>
#else
#include <ryml.hpp>
// <ryml_std.hpp> is needed if interop with std containers is
// desired; ryml itself does not use any STL container.
// For this sample, we will be using std interop, so...
#include <ryml_std.hpp> // optional header, provided for std:: interop
#include <c4/format.hpp> // needed for the examples below
#endif
// these are needed for the examples below
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#ifdef C4_EXCEPTIONS
#include <stdexcept>
#else
#include <csetjmp>
#endif
//-----------------------------------------------------------------------------
/** @cond dev */
// CONTENTS:
//
// (Each function addresses a topic and is fully self-contained. Jump
// to the function to find out about its topic.)
namespace sample {
void sample_lightning_overview(); ///< lightning overview of most common features
void sample_quick_overview(); ///< quick overview of most common features
void sample_substr(); ///< about ryml's string views (from c4core)
void sample_parse_file(); ///< ready-to-go example of parsing a file from disk
void sample_parse_in_place(); ///< parse a mutable YAML source buffer
void sample_parse_in_arena(); ///< parse a read-only YAML source buffer
void sample_parse_reuse_tree(); ///< parse into an existing tree, maybe into a node
void sample_parse_reuse_parser(); ///< reuse an existing parser
void sample_parse_reuse_tree_and_parser(); ///< how to reuse existing trees and parsers
void sample_iterate_trees(); ///< visit individual nodes and iterate through trees
void sample_create_trees(); ///< programatically create trees
void sample_tree_arena(); ///< interact with the tree's serialization arena
void sample_fundamental_types(); ///< serialize/deserialize fundamental types
void sample_empty_null_values(); ///< serialize/deserialize/query empty or null values
void sample_formatting(); ///< control formatting when serializing/deserializing
void sample_base64(); ///< encode/decode base64
void sample_user_scalar_types(); ///< serialize/deserialize scalar (leaf/string) types
void sample_user_container_types(); ///< serialize/deserialize container (map or seq) types
void sample_std_types(); ///< serialize/deserialize STL containers
void sample_float_precision(); ///< control precision of serialized floats
void sample_emit_to_container(); ///< emit to memory, eg a string or vector-like container
void sample_emit_to_stream(); ///< emit to a stream, eg std::ostream
void sample_emit_to_file(); ///< emit to a FILE*
void sample_emit_nested_node(); ///< pick a nested node as the root when emitting
void sample_emit_style(); ///< set the nodes to FLOW/BLOCK format
void sample_json(); ///< JSON parsing and emitting
void sample_anchors_and_aliases(); ///< deal with YAML anchors and aliases
void sample_tags(); ///< deal with YAML type tags
void sample_tag_directives(); ///< deal with YAML tag namespace directives
void sample_docs(); ///< deal with YAML docs
void sample_error_handler(); ///< set a custom error handler
void sample_global_allocator(); ///< set a global allocator for ryml
void sample_per_tree_allocator(); ///< set per-tree allocators
void sample_static_trees(); ///< how to use static trees in ryml
void sample_location_tracking(); ///< track node locations in the parsed source tree
int report_checks();
} /* namespace sample */
int main()
{
sample::sample_lightning_overview();
sample::sample_quick_overview();
sample::sample_substr();
sample::sample_parse_file();
sample::sample_parse_in_place();
sample::sample_parse_in_arena();
sample::sample_parse_reuse_tree();
sample::sample_parse_reuse_parser();
sample::sample_parse_reuse_tree_and_parser();
sample::sample_iterate_trees();
sample::sample_create_trees();
sample::sample_tree_arena();
sample::sample_fundamental_types();
sample::sample_empty_null_values();
sample::sample_formatting();
sample::sample_base64();
sample::sample_user_scalar_types();
sample::sample_user_container_types();
sample::sample_float_precision();
sample::sample_std_types();
sample::sample_emit_to_container();
sample::sample_emit_to_stream();
sample::sample_emit_to_file();
sample::sample_emit_nested_node();
sample::sample_emit_style();
sample::sample_json();
sample::sample_anchors_and_aliases();
sample::sample_tags();
sample::sample_tag_directives();
sample::sample_docs();
sample::sample_error_handler();
sample::sample_global_allocator();
sample::sample_per_tree_allocator();
sample::sample_static_trees();
sample::sample_location_tracking();
return sample::report_checks();
}
/** @endcond */
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C4_SUPPRESS_WARNING_GCC_CLANG_PUSH
C4_SUPPRESS_WARNING_GCC_CLANG("-Wcast-qual")
C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast")
C4_SUPPRESS_WARNING_GCC("-Wuseless-cast")
namespace sample {
/** @addtogroup doc_quickstart
*
* This file does a quick tour of ryml. It has multiple self-contained
* and well-commented samples that illustrate how to use ryml, and how
* it works.
*
* Although this is not a unit test, the samples are written as a
* sequence of actions and predicate checks to better convey what is
* the expected result at any stage. And to ensure the code here is
* correct and up to date, it's also run as part of the CI tests.
*
* If something is unclear, please open an issue or send a pull
* request at https://github.com/biojppm/rapidyaml . If you have an
* issue while using ryml, it is also encouraged to try to reproduce
* the issue here, or look first through the relevant section.
*
* Happy ryml'ing!
*
* ### Some guidance on building
*
* The directories that exist side-by-side with this file contain
* several examples on how to build this with cmake, such that you can
* hit the ground running. See [the relevant section of the main
* README](https://github.com/biojppm/rapidyaml/tree/v0.5.0?tab=readme-ov-file#quickstart-samples)
* for an overview of the different choices. I suggest starting first
* with the `add_subdirectory` example, treating it just like any
* other self-contained cmake project.
*
* Or very quickly, to build and run this sample on your PC, start by
* creating this `CMakeLists.txt`:
* ```cmake
* cmake_minimum_required(VERSION 3.13)
* project(ryml-quickstart LANGUAGES CXX)
* include(FetchContent)
* FetchContent_Declare(ryml
* GIT_REPOSITORY https://github.com/biojppm/rapidyaml.git
* GIT_TAG v0.7.0
* GIT_SHALLOW FALSE # ensure submodules are checked out
* )
* FetchContent_MakeAvailable(ryml)
* add_executable(ryml-quickstart ${ryml_SOURCE_DIR}/samples/quickstart.cpp)
* target_link_libraries(ryml-quickstart ryml::ryml)
* add_custom_target(run ryml-quickstart
* COMMAND $<TARGET_FILE:ryml-quickstart>
* DEPENDS ryml-quickstart
* COMMENT "running: $<TARGET_FILE:ryml-quickstart>")
* ```
* Now run the following commands in the same folder:
* ```bash
* # configure the project
* cmake -S . -B build
* # build and run
* cmake --build build --target ryml-quickstart -j
* # optionally, open in your IDE
* cmake --open build
* ```
*
* @{ */
//-----------------------------------------------------------------------------
// first, some helpers used in this quickstart
/** @defgroup doc_sample_helpers Sample helpers
* @brief Functions and classes used in the examples of this sample.
* @addtogroup doc_sample_helpers
* @{ */
bool report_check(int line, const char *predicate, bool result);
// GCC 4.8 has a problem with the CHECK() macro
#ifndef _DOXYGEN_
#if (defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
/// a quick'n'dirty assertion to verify a predicate
#define CHECK CheckPredicate{__FILE__, __LINE__}
struct CheckPredicate
{
const char *file;
const int line;
void operator() (bool predicate) const
{
if (!report_check(line, nullptr, predicate))
{
#ifdef RYML_DBG
RYML_DEBUG_BREAK();
#endif
}
}
};
#else
/** a quick'n'dirty assertion to verify a predicate */
#define CHECK(predicate) do { if(!report_check(__LINE__, #predicate, (predicate))) { RYML_DEBUG_BREAK(); } } while(0)
#endif
#else
// enable doxygen to link to the functions called inside CHECK()
#define CHECK(predicate) assert(predicate)
#endif
// helper functions for sample_parse_file()
template<class CharContainer> CharContainer file_get_contents(const char *filename);
template<class CharContainer> size_t file_get_contents(const char *filename, CharContainer *v);
template<class CharContainer> void file_put_contents(const char *filename, CharContainer const& v, const char* access="wb");
void file_put_contents(const char *filename, const char *buf, size_t sz, const char* access);
/** this is an example error handler, required for some of the
* quickstart examples. */
struct ErrorHandlerExample
{
ryml::Callbacks callbacks();
C4_NORETURN void on_error(const char* msg, size_t len, ryml::Location loc);
C4_NORETURN static void s_error(const char* msg, size_t len, ryml::Location loc, void *this_);
template<class Fn> C4_NODISCARD bool check_error_occurs(Fn &&fn) const;
template<class Fn> C4_NODISCARD bool check_assertion_occurs(Fn &&fn) const;
void check_effect(bool committed) const;
ErrorHandlerExample() : defaults(ryml::get_callbacks()) {}
ryml::Callbacks defaults;
};
/** Shows how to easily create a scoped error handler. */
struct ScopedErrorHandlerExample : public ErrorHandlerExample
{
ScopedErrorHandlerExample() : ErrorHandlerExample() { ryml::set_callbacks(callbacks()); check_effect(true); }
~ScopedErrorHandlerExample() { ryml::set_callbacks(defaults); check_effect(false); }
};
/** @} */ // doc_sample_helpers
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** a lightning tour over most features
* see @ref sample_quick_overview */
void sample_lightning_overview()
{
// Parse YAML code in place, potentially mutating the buffer:
char yml_buf[] = "{foo: 1, bar: [2, 3], john: doe}";
ryml::Tree tree = ryml::parse_in_place(yml_buf);
// read from the tree:
ryml::NodeRef bar = tree["bar"];
CHECK(bar[0].val() == "2");
CHECK(bar[1].val() == "3");
CHECK(bar[0].val().str == yml_buf + 15); // points at the source buffer
CHECK(bar[1].val().str == yml_buf + 18);
// deserializing:
int bar0 = 0, bar1 = 0;
bar[0] >> bar0;
bar[1] >> bar1;
CHECK(bar0 == 2);
CHECK(bar1 == 3);
// serializing:
bar[0] << 10; // creates a string in the tree's arena
bar[1] << 11;
CHECK(bar[0].val() == "10");
CHECK(bar[1].val() == "11");
// add nodes
bar.append_child() << 12; // see also operator= (explanation below)
CHECK(bar[2].val() == "12");
// emit tree
// to std::string
CHECK(ryml::emitrs_yaml<std::string>(tree) == R"({foo: 1,bar: [10,11,12],john: doe})");
std::cout << tree; // emit to ostream
ryml::emit_yaml(tree, stdout); // emit to FILE*
// emit node
ryml::ConstNodeRef foo = tree["foo"];
// to std::string
CHECK(ryml::emitrs_yaml<std::string>(foo) == "foo: 1\n");
std::cout << foo; // emit node to ostream
ryml::emit_yaml(foo, stdout); // emit node to FILE*
}
//-----------------------------------------------------------------------------
/** a brief tour over most features */
void sample_quick_overview()
{
// Parse YAML code in place, potentially mutating the buffer:
char yml_buf[] = R"(
foo: 1
bar: [2, 3]
john: doe)";
ryml::Tree tree = ryml::parse_in_place(yml_buf);
// The resulting tree contains only views to the parsed string. If
// the string was parsed in place, then the string must outlive
// the tree! This works in this case because `yml_buf` and `tree`
// live on the same scope, so have the same lifetime.
// It is also possible to:
//
// - parse a read-only buffer using parse_in_arena(). This
// copies the YAML buffer to the tree's arena, and spares the
// headache of the string's lifetime.
//
// - reuse an existing tree (advised)
//
// - reuse an existing parser (advised)
//
// - parse into an existing node deep in a tree
//
// Note: it will always be significantly faster to parse in place
// and reuse tree+parser.
//
// Below you will find samples that show how to achieve reuse; but
// please note that for brevity and clarity, many of the examples
// here are parsing in the arena, and not reusing tree or parser.
//------------------------------------------------------------------
// API overview
// ryml has a two-level API:
//
// The lower level index API is based on the indices of nodes,
// where the node's id is the node's position in the tree's data
// array. This API is very efficient, but somewhat difficult to use:
ryml::id_type root_id = tree.root_id();
ryml::id_type bar_id = tree.find_child(root_id, "bar"); // need to get the index right
CHECK(tree.is_map(root_id)); // all of the index methods are in the tree
CHECK(tree.is_seq(bar_id)); // ... and receive the subject index
// The node API is a lightweight abstraction sitting on top of the
// index API, but offering a much more convenient interaction:
ryml::ConstNodeRef root = tree.rootref(); // a const node reference
ryml::ConstNodeRef bar = tree["bar"];
CHECK(root.is_map());
CHECK(bar.is_seq());
// A node ref is a lightweight handle to the tree and associated id:
CHECK(root.tree() == &tree); // a node ref points at its tree, WITHOUT refcount
CHECK(root.id() == root_id); // a node ref's id is the index of the node
CHECK(bar.id() == bar_id); // a node ref's id is the index of the node
// The node API translates very cleanly to the index API, so most
// of the code examples below are using the node API.
// WARNING. A node ref holds a raw pointer to the tree. Care must
// be taken to ensure the lifetimes match, so that a node will
// never access the tree after the goes out of scope.
//------------------------------------------------------------------
// To read the parsed tree
// ConstNodeRef::operator[] does a lookup, is O(num_children[node]).
CHECK(tree["foo"].is_keyval());
CHECK(tree["foo"].val() == "1"); // get the val of a node (must be leaf node, otherwise it is a container and has no val)
CHECK(tree["foo"].key() == "foo"); // get the key of a node (must be child of a map, otherwise it has no key)
CHECK(tree["bar"].is_seq());
CHECK(tree["bar"].has_key());
CHECK(tree["bar"].key() == "bar");
// maps use string keys, seqs use index keys:
CHECK(tree["bar"][0].val() == "2");
CHECK(tree["bar"][1].val() == "3");
CHECK(tree["john"].val() == "doe");
// An index key is the position of the child within its parent,
// so even maps can also use int keys, if the key position is
// known.
CHECK(tree[0].id() == tree["foo"].id());
CHECK(tree[1].id() == tree["bar"].id());
CHECK(tree[2].id() == tree["john"].id());
// Tree::operator[](int) searches a ***root*** child by its position.
CHECK(tree[0].id() == tree["foo"].id()); // 0: first child of root
CHECK(tree[1].id() == tree["bar"].id()); // 1: second child of root
CHECK(tree[2].id() == tree["john"].id()); // 2: third child of root
// NodeRef::operator[](int) searches a ***node*** child by its position:
CHECK(bar[0].val() == "2"); // 0 means first child of bar
CHECK(bar[1].val() == "3"); // 1 means second child of bar
// NodeRef::operator[](string):
// A string key is the key of the node: lookup is by name. So it
// is only available for maps, and it is NOT available for seqs,
// since seq members do not have keys.
CHECK(tree["foo"].key() == "foo");
CHECK(tree["bar"].key() == "bar");
CHECK(tree["john"].key() == "john");
CHECK(bar.is_seq());
// CHECK(bar["BOOM!"].is_seed()); // error, seqs do not have key lookup
// Note that maps can also use index keys as well as string keys:
CHECK(root["foo"].id() == root[0].id());
CHECK(root["bar"].id() == root[1].id());
CHECK(root["john"].id() == root[2].id());
// IMPORTANT. The ryml tree uses an index-based linked list for
// storing children, so the complexity of
// `Tree::operator[csubstr]` and `Tree::operator[id_type]` is O(n),
// linear on the number of root children. If you use
// `Tree::operator[]` with a large tree where the root has many
// children, you will see a performance hit.
//
// To avoid this hit, you can create your own accelerator
// structure. For example, before doing a lookup, do a single
// traverse at the root level to fill an `map<csubstr,id_type>`
// mapping key names to node indices; with a node index, a lookup
// (via `Tree::get()`) is O(1), so this way you can get O(log n)
// lookup from a key. (But please do not use `std::map` if you
// care about performance; use something else like a flat map or
// sorted vector).
//
// As for node refs, the difference from `NodeRef::operator[]` and
// `ConstNodeRef::operator[]` to `Tree::operator[]` is that the
// latter refers to the root node, whereas the former are invoked
// on their target node. But the lookup process works the same for
// both and their algorithmic complexity is the same: they are
// both linear in the number of direct children. But of course,
// depending on the data, that number may be very different from
// one to another.
//------------------------------------------------------------------
// Hierarchy:
{
ryml::ConstNodeRef foo = root.first_child();
ryml::ConstNodeRef john = root.last_child();
CHECK(tree.size() == 6); // O(1) number of nodes in the tree
CHECK(root.num_children() == 3); // O(num_children[root])
CHECK(foo.num_siblings() == 3); // O(num_children[parent(foo)])
CHECK(foo.parent().id() == root.id()); // parent() is O(1)
CHECK(root.first_child().id() == root["foo"].id()); // first_child() is O(1)
CHECK(root.last_child().id() == root["john"].id()); // last_child() is O(1)
CHECK(john.first_sibling().id() == foo.id());
CHECK(foo.last_sibling().id() == john.id());
// prev_sibling(), next_sibling(): (both are O(1))
CHECK(foo.num_siblings() == root.num_children());
CHECK(foo.prev_sibling().id() == ryml::NONE); // foo is the first_child()
CHECK(foo.next_sibling().key() == "bar");
CHECK(foo.next_sibling().next_sibling().key() == "john");
CHECK(foo.next_sibling().next_sibling().next_sibling().id() == ryml::NONE); // john is the last_child()
}
//------------------------------------------------------------------
// Iterating:
{
ryml::csubstr expected_keys[] = {"foo", "bar", "john"};
// iterate children using the high-level node API:
{
ryml::id_type count = 0;
for(ryml::ConstNodeRef const& child : root.children())
CHECK(child.key() == expected_keys[count++]);
}
// iterate siblings using the high-level node API:
{
ryml::id_type count = 0;
for(ryml::ConstNodeRef const& child : root["foo"].siblings())
CHECK(child.key() == expected_keys[count++]);
}
// iterate children using the lower-level tree index API:
{
ryml::id_type count = 0;
for(ryml::id_type child_id = tree.first_child(root_id); child_id != ryml::NONE; child_id = tree.next_sibling(child_id))
CHECK(tree.key(child_id) == expected_keys[count++]);
}
// iterate siblings using the lower-level tree index API:
// (notice the only difference from above is in the loop
// preamble, which calls tree.first_sibling(bar_id) instead of
// tree.first_child(root_id))
{
ryml::id_type count = 0;
for(ryml::id_type child_id = tree.first_sibling(bar_id); child_id != ryml::NONE; child_id = tree.next_sibling(child_id))
CHECK(tree.key(child_id) == expected_keys[count++]);
}
}
//------------------------------------------------------------------
// Gotchas:
// ryml uses assertions to prevent you from trying to obtain
// things that do not exist. For example:
{
ryml::ConstNodeRef seq_node = tree["bar"];
ryml::ConstNodeRef val_node = seq_node[0];
CHECK(seq_node.is_seq()); // seq is a container
CHECK(!seq_node.has_val()); // ... so it has no val
//CHECK(seq_node.val() == BOOM!); // ... so attempting to get a val is undefined behavior
CHECK(val_node.parent() == seq_node); // belongs to a seq
CHECK(!val_node.has_key()); // ... so it has no key
//CHECK(val_node.key() == BOOM!); // ... so attempting to get a key is undefined behavior
CHECK(val_node.is_val()); // this node is a val
//CHECK(val_node.first_child() == BOOM!); // ... so attempting to get a child is undefined behavior
// assertions are also present in methods that /may/ read the val:
CHECK(seq_node.is_seq()); // seq is a container
//CHECK(seq_node.val_is_null() BOOM!); // so cannot get the val to check
}
// By default, assertions are enabled unless the NDEBUG macro is
// defined (which happens in release builds).
//
// This adheres to the pay-only-for-what-you-use philosophy: if
// you are sure that your intent is correct, why would you need to
// pay the runtime cost for the assertions?
//
// The downside, of course, is that when you are not sure, release
// builds may be doing something crazy.
//
// So in that case, you can either use the appropriate ryml
// predicates to check your intent (as in the examples above), or
// you can override this behavior and enable/disable assertions,
// by defining the macro RYML_USE_ASSERT to a proper value (see
// c4/yml/common.hpp).
//
// Also, to be clear, this does not apply to parse errors
// occurring when the YAML is parsed. Checking for these errors is
// always enabled and cannot be switched off.
//------------------------------------------------------------------
// Deserializing: use operator>>
{
int foo = 0, bar0 = 0, bar1 = 0;
std::string john_str;
std::string bar_str;
root["foo"] >> foo;
root["bar"][0] >> bar0;
root["bar"][1] >> bar1;
root["john"] >> john_str; // requires from_chars(std::string). see serialization samples below.
root["bar"] >> ryml::key(bar_str); // to deserialize the key, use the tag function ryml::key()
CHECK(foo == 1);
CHECK(bar0 == 2);
CHECK(bar1 == 3);
CHECK(john_str == "doe");
CHECK(bar_str == "bar");
}
//------------------------------------------------------------------
// Modifying existing nodes: operator= vs operator<<
// As implied by its name, ConstNodeRef is a reference to a const
// node. It can be used to read from the node, but not write to it
// or modify the hierarchy of the node. If any modification is
// desired then a NodeRef must be used instead:
ryml::NodeRef wroot = tree.rootref(); // writeable root
// operator= assigns an existing string to the receiving node.
// The contents are NOT copied, and the string pointer will be in
// effect until the tree goes out of scope! So BEWARE to only
// assign from strings outliving the tree.
wroot["foo"] = "says you";
wroot["bar"][0] = "-2";
wroot["bar"][1] = "-3";
wroot["john"] = "ron";
// Now the tree is _pointing_ at the memory of the strings above.
// In this case it is OK because those are static strings, located
// in the executable's static section, and will outlive the tree.
CHECK(root["foo"].val() == "says you");
CHECK(root["bar"][0].val() == "-2");
CHECK(root["bar"][1].val() == "-3");
CHECK(root["john"].val() == "ron");
// But WATCHOUT: do not assign from temporary objects:
// {
// std::string crash("will dangle");
// root["john"] = ryml::to_csubstr(crash);
// }
// CHECK(root["john"] == "dangling"); // CRASH! the string was deallocated
// operator<<: for cases where the lifetime of the string is
// problematic WRT the tree, you can create and save a string in
// the tree using operator<<. It first serializes values to a
// string arena owned by the tree, then assigns the serialized
// string to the receiving node. This avoids constraints with the
// lifetime, since the arena lives with the tree.
CHECK(tree.arena().empty());
wroot["foo"] << "says who"; // requires to_chars(). see serialization samples below.
wroot["bar"][0] << 20;
wroot["bar"][1] << 30;
wroot["john"] << "deere";
CHECK(root["foo"].val() == "says who");
CHECK(root["bar"][0].val() == "20");
CHECK(root["bar"][1].val() == "30");
CHECK(root["john"].val() == "deere");
CHECK(tree.arena() == "says who2030deere"); // the result of serializations to the tree arena
// using operator<< instead of operator=, the crash above is avoided:
{
std::string ok("in_scope");
// root["john"] = ryml::to_csubstr(ok); // don't, will dangle
wroot["john"] << ryml::to_csubstr(ok); // OK, copy to the tree's arena
}
CHECK(root["john"].val() == "in_scope"); // OK!
// serializing floating points:
wroot["float"] << 2.4;
// to force a particular precision or float format:
// (see sample_float_precision() and sample_formatting())
wroot["digits"] << ryml::fmt::real(2.4, /*num_digits*/6, ryml::FTOA_FLOAT);
CHECK(tree.arena() == "says who2030deerein_scope2.42.400000"); // the result of serializations to the tree arena
//------------------------------------------------------------------
// Adding new nodes:
// adding a keyval node to a map:
CHECK(root.num_children() == 5);
wroot["newkeyval"] = "shiny and new"; // using these strings
wroot.append_child() << ryml::key("newkeyval (serialized)") << "shiny and new (serialized)"; // serializes and assigns the serialization
CHECK(root.num_children() == 7);
CHECK(root["newkeyval"].key() == "newkeyval");
CHECK(root["newkeyval"].val() == "shiny and new");
CHECK(root["newkeyval (serialized)"].key() == "newkeyval (serialized)");
CHECK(root["newkeyval (serialized)"].val() == "shiny and new (serialized)");
CHECK( ! tree.in_arena(root["newkeyval"].key())); // it's using directly the static string above
CHECK( ! tree.in_arena(root["newkeyval"].val())); // it's using directly the static string above
CHECK( tree.in_arena(root["newkeyval (serialized)"].key())); // it's using a serialization of the string above
CHECK( tree.in_arena(root["newkeyval (serialized)"].val())); // it's using a serialization of the string above
// adding a val node to a seq:
CHECK(root["bar"].num_children() == 2);
wroot["bar"][2] = "oh so nice";
wroot["bar"][3] << "oh so nice (serialized)";
CHECK(root["bar"].num_children() == 4);
CHECK(root["bar"][2].val() == "oh so nice");
CHECK(root["bar"][3].val() == "oh so nice (serialized)");
// adding a seq node:
CHECK(root.num_children() == 7);
wroot["newseq"] |= ryml::SEQ;
wroot.append_child() << ryml::key("newseq (serialized)") |= ryml::SEQ;
CHECK(root.num_children() == 9);
CHECK(root["newseq"].num_children() == 0);
CHECK(root["newseq"].is_seq());
CHECK(root["newseq (serialized)"].num_children() == 0);
CHECK(root["newseq (serialized)"].is_seq());
// adding a map node:
CHECK(root.num_children() == 9);
wroot["newmap"] |= ryml::MAP;
wroot.append_child() << ryml::key("newmap (serialized)") |= ryml::MAP;
CHECK(root.num_children() == 11);
CHECK(root["newmap"].num_children() == 0);
CHECK(root["newmap"].is_map());
CHECK(root["newmap (serialized)"].num_children() == 0);
CHECK(root["newmap (serialized)"].is_map());
//
// When the tree is mutable, operator[] first searches the tree
// for the does not mutate the tree until the returned node is
// written to.
//
// Until such time, the NodeRef object keeps in itself the required
// information to write to the proper place in the tree. This is
// called being in a "seed" state.
//
// This means that passing a key/index which does not exist will
// not mutate the tree, but will instead store (in the node) the
// proper place of the tree to be able to do so, if and when it is
// required. This is why the node is said to be in "seed" state -
// it allows creating the entry in the tree in the future.
//
// This is a significant difference from eg, the behavior of
// std::map, which mutates the map immediately within the call to
// operator[].
//
// All of the points above apply only if the tree is mutable. If
// the tree is const, then a NodeRef cannot be obtained from it;
// only a ConstNodeRef, which can never be used to mutate the
// tree.
//
CHECK(!root.has_child("I am not nothing"));
ryml::NodeRef nothing;
CHECK(nothing.invalid()); // invalid because it points at nothing
nothing = wroot["I am nothing"];
CHECK(!nothing.invalid()); // points at the tree, and a specific place in the tree
CHECK(nothing.is_seed()); // ... but nothing is there yet.
CHECK(!root.has_child("I am nothing")); // same as above
CHECK(!nothing.readable()); // ... and this node cannot be used to
// read anything from the tree
ryml::NodeRef something = wroot["I am something"];
ryml::ConstNodeRef constsomething = wroot["I am something"];
CHECK(!root.has_child("I am something")); // same as above
CHECK(!something.invalid());
CHECK(something.is_seed()); // same as above
CHECK(!something.readable()); // same as above
CHECK(constsomething.invalid()); // NOTE: because a ConstNodeRef cannot be
// used to mutate a tree, it is only valid()
// if it is pointing at an existing node.
something = "indeed"; // this will commit the seed to the tree, mutating at the proper place
CHECK(root.has_child("I am something"));
CHECK(root["I am something"].val() == "indeed");
CHECK(!something.invalid()); // it was already valid
CHECK(!something.is_seed()); // now the tree has this node, so the
// ref is no longer a seed
CHECK(something.readable()); // and it is now readable
//
// now the constref is also valid (but it needs to be reassigned):
ryml::ConstNodeRef constsomethingnew = wroot["I am something"];
CHECK(!constsomethingnew.invalid());
CHECK(constsomethingnew.readable());
// note that the old constref is now stale, because it only keeps
// the state at creation:
CHECK(constsomething.invalid());
CHECK(!constsomething.readable());
//
// -----------------------------------------------------------
// Remember: a seed node cannot be used to read from the tree!
// -----------------------------------------------------------
//
// The seed node needs to be created and become readable first.
//
// Trying to invoke any tree-reading method on a node that is not
// readable will cause an assertion (see RYML_USE_ASSERT).
//
// It is your responsibility to verify that the preconditions are
// met. If you are not sure about the structure of your data,
// write your code defensively to signify your full intent:
//
ryml::NodeRef wbar = wroot["bar"];
if(wbar.readable() && wbar.is_seq()) // .is_seq() requires .readable()
{
CHECK(wbar[0].readable() && wbar[0].val() == "20");
CHECK( ! wbar[100].readable());
CHECK( ! wbar[100].readable() || wbar[100].val() == "100"); // <- no crash because it is not .readable(), so never tries to call .val()
// this would work as well:
CHECK( ! wbar[0].is_seed() && wbar[0].val() == "20");
CHECK(wbar[100].is_seed() || wbar[100].val() == "100");
}
//------------------------------------------------------------------
// .operator[]() vs .at()
// (Const)NodeRef::operator[]() is an analogue to std::vector::operator[].
// (Const)NodeRef::at() is an analogue to std::vector::at()
//
// at() will always check the subject node is .readable().
//
// [] is meant for the happy path, and unverified in Release
// builds.
{
// in this example we will be checking errors, so set up a
// temporary error handler to catch them:
ScopedErrorHandlerExample errh;
// instantiate the tree after errh
ryml::Tree err_tree = ryml::parse_in_arena("{foo: bar}");
// ... so that the tree uses the current callbacks:
CHECK(err_tree.callbacks() == errh.callbacks());
// node does not exist, only a seed node
ryml::NodeRef seed_node = err_tree["this"];
// ... therefore not .readable()
CHECK(!seed_node.readable());
// using .at() reliably produces an error:
CHECK(errh.check_error_occurs([&]{
return seed_node.at("is").at("an").at("invalid").at("operation");
// ^
// error occurs here because it is unreadable
}));
// ... but using [] fails only when RYML_USE_ASSERT is
// defined. otherwise, it's the dreaded Undefined Behavior:
CHECK(errh.check_assertion_occurs([&]{
return seed_node["is"]["an"]["invalid"]["operation"];
// ^
// assertion occurs here because it is unreadable
}));
}
//------------------------------------------------------------------
// Emitting:
ryml::csubstr expected_result = R"(foo: says who
bar: [20,30,oh so nice,oh so nice (serialized)]
john: in_scope
float: 2.4
digits: 2.400000
newkeyval: shiny and new
newkeyval (serialized): shiny and new (serialized)
newseq: []
newseq (serialized): []
newmap: {}
newmap (serialized): {}
I am something: indeed
)";
// emit to a FILE*
ryml::emit_yaml(tree, stdout);
// emit to a stream
std::stringstream ss;
ss << tree;
std::string stream_result = ss.str();
// emit to a buffer:
std::string str_result = ryml::emitrs_yaml<std::string>(tree);
// can emit to any given buffer:
char buf[1024];
ryml::csubstr buf_result = ryml::emit_yaml(tree, buf);
// now check
CHECK(buf_result == expected_result);
CHECK(str_result == expected_result);
CHECK(stream_result == expected_result);
// There are many possibilities to emit to buffer;
// please look at the emit sample functions below.
//------------------------------------------------------------------
// ConstNodeRef vs NodeRef
ryml::NodeRef noderef = tree["bar"][0];
ryml::ConstNodeRef constnoderef = tree["bar"][0];
// ConstNodeRef cannot be used to mutate the tree:
//constnoderef = "21"; // compile error
//constnoderef << "22"; // compile error
// ... but a NodeRef can:
noderef = "21"; // ok, can assign because it's not const
CHECK(tree["bar"][0].val() == "21");
noderef << "22"; // ok, can serialize and assign because it's not const
CHECK(tree["bar"][0].val() == "22");
// it is not possible to obtain a NodeRef from a ConstNodeRef:
// noderef = constnoderef; // compile error
// it is always possible to obtain a ConstNodeRef from a NodeRef:
constnoderef = noderef; // ok can assign const <- nonconst
// If a tree is const, then only ConstNodeRef's can be
// obtained from that tree:
ryml::Tree const& consttree = tree;
//noderef = consttree["bar"][0]; // compile error
noderef = tree["bar"][0]; // ok
constnoderef = consttree["bar"][0]; // ok
// ConstNodeRef and NodeRef can be compared for equality.
// Equality means they point at the same node.
CHECK(constnoderef == noderef);
CHECK(!(constnoderef != noderef));
//------------------------------------------------------------------
// Getting the location of nodes in the source:
//
// Location tracking is opt-in:
ryml::EventHandlerTree evt_handler = {};
ryml::Parser parser(&evt_handler, ryml::ParserOptions().locations(true));
// Now the parser will start by building the accelerator structure:
ryml::Tree tree2 = parse_in_arena(&parser, "expected.yml", expected_result);
// ... and use it when querying
ryml::ConstNodeRef subject_node = tree2["bar"][1];
CHECK(subject_node.val() == "30");
ryml::Location loc = parser.location(subject_node);
CHECK(parser.location_contents(loc).begins_with("30"));
CHECK(loc.line == 1u);
CHECK(loc.col == 9u);
// For further details in location tracking,
// refer to the sample function below.
//------------------------------------------------------------------
// Dealing with UTF8
ryml::Tree langs = ryml::parse_in_arena(R"(
en: Planet (Gas)
fr: Planète (Gazeuse)
ru: Планета (Газ)
ja: 惑星(ガス)
zh: 行星(气体)
# UTF8 decoding only happens in double-quoted strings,
# as per the YAML standard
decode this: "\u263A \xE2\x98\xBA"
and this as well: "\u2705 \U0001D11E"
not decoded: '\u263A \xE2\x98\xBA'
neither this: '\u2705 \U0001D11E'
)");
// in-place UTF8 just works:
CHECK(langs["en"].val() == "Planet (Gas)");
CHECK(langs["fr"].val() == "Planète (Gazeuse)");
CHECK(langs["ru"].val() == "Планета (Газ)");
CHECK(langs["ja"].val() == "惑星(ガス)");
CHECK(langs["zh"].val() == "行星(气体)");
// and \x \u \U codepoints are decoded, but only when they appear
// inside double-quoted strings, as dictated by the YAML
// standard:
CHECK(langs["decode this"].val() == "☺ ☺");
CHECK(langs["and this as well"].val() == "✅ 𝄞");
CHECK(langs["not decoded"].val() == "\\u263A \\xE2\\x98\\xBA");
CHECK(langs["neither this"].val() == "\\u2705 \\U0001D11E");
}
//-----------------------------------------------------------------------------
/** demonstrate usage of ryml::substr and ryml::csubstr
*
* These types are imported from the c4core library into the ryml
* namespace You may have noticed above the use of a `csubstr`
* class. This class is defined in another library,
* [c4core](https://github.com/biojppm/c4core), which is imported by
* ryml. This is a library I use with my projects consisting of
* multiplatform low-level utilities. One of these is `c4::csubstr`
* (the name comes from "constant substring") which is a non-owning
* read-only string view, with many methods that make it practical to
* use (I would certainly argue more practical than `std::string`). In
* fact, `c4::csubstr` and its writeable counterpart `c4::substr` are
* the workhorses of the ryml parsing and serialization code.
*
* @see doc_substr */
void sample_substr()
{
// substr is a mutable view: pointer and length to a string in memory.
// csubstr is a const-substr (immutable).
// construct from explicit args
{
const char foobar_str[] = "foobar";
auto s = ryml::csubstr(foobar_str, strlen(foobar_str));
CHECK(s == "foobar");
CHECK(s.size() == 6);
CHECK(s.data() == foobar_str);
CHECK(s.size() == s.len);
CHECK(s.data() == s.str);
}
// construct from a string array
{
const char foobar_str[] = "foobar";
ryml::csubstr s = foobar_str;
CHECK(s == "foobar");
CHECK(s != "foobar0");
CHECK(s.size() == 6); // does not include the terminating \0
CHECK(s.data() == foobar_str);
CHECK(s.size() == s.len);
CHECK(s.data() == s.str);
}
// you can also declare directly in-place from an array:
{
ryml::csubstr s = "foobar";
CHECK(s == "foobar");
CHECK(s != "foobar0");
CHECK(s.size() == 6);
CHECK(s.size() == s.len);
CHECK(s.data() == s.str);
}
// construct from a C-string:
//
// Since the input is only a pointer, the string length can only
// be found with a call to strlen(). To make this cost evident, we
// require calling to_csubstr():
{
const char *foobar_str = "foobar";
ryml::csubstr s = ryml::to_csubstr(foobar_str);
CHECK(s == "foobar");
CHECK(s != "foobar0");
CHECK(s.size() == 6);
CHECK(s.size() == s.len);
CHECK(s.data() == s.str);
}
// construct from a std::string: same approach as above.
// requires inclusion of the <ryml/std/string.hpp> header
// or of the umbrella header <ryml_std.hpp>.
//
// not including <string> in the default header is a deliberate
// design choice to avoid including the heavy std:: allocation
// machinery
{
std::string foobar_str = "foobar";
ryml::csubstr s = ryml::to_csubstr(foobar_str); // defined in <ryml/std/string.hpp>
CHECK(s == "foobar");
CHECK(s != "foobar0");
CHECK(s.size() == 6);