-
Notifications
You must be signed in to change notification settings - Fork 106
/
quickstart.cpp
4063 lines (3724 loc) · 163 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
//
// This file does a quick tour of ryml. It has multiple self-contained
// and 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.
//
// 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. I suggest starting first with the
// add_subdirectory example, treating it just like any other
// self-contained cmake project.
//
// 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!
//-----------------------------------------------------------------------------
// 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
// <ryml_std.hpp> is only needed if interop with std types 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. BUT when used, needs to be included BEFORE ryml.hpp
#include <ryml.hpp>
#include <c4/format.hpp> // needed only needed for the examples below
#endif
// these are only needed for the examples below
#include <iostream>
#include <sstream>
#include <vector>
#include <array>
#include <map>
//-----------------------------------------------------------------------------
// 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_quick_overview(); ///< briefly skim over most of the 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_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_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_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_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_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_formatting();
sample::sample_base64();
sample::sample_user_scalar_types();
sample::sample_user_container_types();
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_json();
sample::sample_anchors_and_aliases();
sample::sample_tags();
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();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace sample {
bool report_check(const char *file, int line, const char *predicate, bool result);
#ifdef __GNUC__
#if __GNUC__ == 4 && __GNUC_MINOR__ >= 8
struct CheckPredicate {
const char *file;
const int line;
void operator ()(bool predicate) const {
if (!report_check(file, line, nullptr, predicate)) { C4_DEBUG_BREAK(); }
}
};
#define CHECK CheckPredicate{__FILE__, __LINE__}
#endif
#endif
#if !defined(CHECK)
/// a quick'n'dirty assertion to verify a predicate
#define CHECK(predicate) do { if(!report_check(__FILE__, __LINE__, #predicate, (predicate))) { C4_DEBUG_BREAK(); } } while(0)
#endif
//-----------------------------------------------------------------------------
/** a brief tour over most features */
void sample_quick_overview()
{
// Parse YAML code in place, potentially mutating the buffer.
// It is also possible to:
// - parse a read-only buffer using parse_in_arena()
// - reuse an existing tree (advised)
// - reuse an existing parser (advised)
char yml_buf[] = "{foo: 1, bar: [2, 3], john: doe}";
ryml::Tree tree = ryml::parse_in_place(ryml::substr(yml_buf));
// Note: it will always be significantly faster to use mutable
// buffers 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 immutable buffers, 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:
size_t root_id = tree.root_id();
size_t 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::NodeRef root = tree.rootref();
ryml::NodeRef bar = tree["bar"];
CHECK(root.is_map());
CHECK(bar.is_seq());
// NodeRef is a lightweight handle to the tree and associated id:
CHECK(root.tree() == &tree); // NodeRef points at its tree, WITHOUT refcount
CHECK(root.id() == root_id); // NodeRef's id is the index of the node
CHECK(bar.id() == bar_id); // NodeRef'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.
// One significant point of the node API is that it 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 tree
// went out of scope.
//------------------------------------------------------------------
// To read the parsed tree
// Node::operator[] does a lookup, is O(num_children[node]).
// maps use string keys, seqs use integral keys.
CHECK(tree["foo"].is_keyval());
CHECK(tree["foo"].key() == "foo");
CHECK(tree["foo"].val() == "1");
CHECK(tree["bar"].is_seq());
CHECK(tree["bar"].has_key());
CHECK(tree["bar"].key() == "bar");
CHECK(tree["bar"][0].val() == "2");
CHECK(tree["bar"][1].val() == "3");
CHECK(tree["john"].val() == "doe");
// An integral 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: first child of root
CHECK(tree[2].id() == tree["john"].id()); // 2: first child of root
// NodeRef::operator[](int) searches a node child by its position
// on __the node__'s children list:
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());
// Please note that since a ryml tree uses indexed linked lists for storing
// children, the complexity of `Tree::operator[csubstr]` and
// `Tree::operator[size_t]` is linear on the number of root children. If you use
// it with a large tree where the root has many children, you may get 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,size_t>` 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 `NodeRef`, the difference from `NodeRef::operator[]`
// to `Tree::operator[]` is that the latter refers to the root node, whereas
// the former can be invoked on any node. But the lookup process is the same for
// both and their algorithmic complexity is the same: they are both linear in
// the number of direct children; but depending on the data, that number may
// be very different from one to another.
//------------------------------------------------------------------
// Hierarchy:
{
ryml::NodeRef foo = root.first_child();
ryml::NodeRef 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:
{
size_t count = 0;
for(ryml::NodeRef const& child : root.children())
CHECK(child.key() == expected_keys[count++]);
}
// iterate siblings using the high-level node API:
{
size_t count = 0;
for(ryml::NodeRef const& child : root["foo"].siblings())
CHECK(child.key() == expected_keys[count++]);
}
// iterate children using the lower-level tree index API:
{
size_t count = 0;
for(size_t 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))
{
size_t count = 0;
for(size_t 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:
CHECK(!tree["bar"].has_val()); // seq is a container, so no val
CHECK(!tree["bar"][0].has_key()); // belongs to a seq, so no key
CHECK(!tree["bar"][1].has_key()); // belongs to a seq, so no key
//CHECK(tree["bar"].val() == BOOM!); // ... so attempting to get a val is undefined behavior
//CHECK(tree["bar"][0].key() == BOOM!); // ... so attempting to get a key is undefined behavior
//CHECK(tree["bar"][1].key() == BOOM!); // ... so attempting to get a key is undefined behavior
//------------------------------------------------------------------
// Deserializing: use operator>>
{
int foo = 0, bar0 = 0, bar1 = 0;
std::string john;
root["foo"] >> foo;
root["bar"][0] >> bar0;
root["bar"][1] >> bar1;
root["john"] >> john; // requires from_chars(std::string). see serialization samples below.
CHECK(foo == 1);
CHECK(bar0 == 2);
CHECK(bar1 == 3);
CHECK(john == "doe");
}
//------------------------------------------------------------------
// Modifying existing nodes: operator<< vs operator=
// operator= assigns an existing string to the receiving node.
// This pointer will be in effect until the tree goes out of scope
// so beware to only assign from strings outliving the tree.
root["foo"] = "says you";
root["bar"][0] = "-2";
root["bar"][1] = "-3";
root["john"] = "ron";
// Now the tree is _pointing_ at the memory of the strings above.
// That is OK because those are static strings 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");
// 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<< first serializes the input to the tree's arena, 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());
root["foo"] << "says who"; // requires to_chars(). see serialization samples below.
root["bar"][0] << 20;
root["bar"][1] << 30;
root["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
root["john"] << ryml::to_csubstr(ok); // OK, copy to the tree's arena
}
CHECK(root["john"] == "in_scope"); // OK!
CHECK(tree.arena() == "says who2030deerein_scope"); // the result of serializations to the tree arena
//------------------------------------------------------------------
// Adding new nodes:
// adding a keyval node to a map:
CHECK(root.num_children() == 3);
root["newkeyval"] = "shiny and new"; // using these strings
root.append_child() << ryml::key("newkeyval (serialized)") << "shiny and new (serialized)"; // serializes and assigns the serialization
CHECK(root.num_children() == 5);
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( ! root["newkeyval"].key().is_sub(tree.arena())); // it's using directly the static string above
CHECK( ! root["newkeyval"].val().is_sub(tree.arena())); // it's using directly the static string above
CHECK( root["newkeyval (serialized)"].key().is_sub(tree.arena())); // it's using a serialization of the string above
CHECK( root["newkeyval (serialized)"].val().is_sub(tree.arena())); // it's using a serialization of the string above
// adding a val node to a seq:
CHECK(root["bar"].num_children() == 2);
root["bar"][2] = "oh so nice";
root["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() == 5);
root["newseq"] |= ryml::SEQ;
root.append_child() << ryml::key("newseq (serialized)") |= ryml::SEQ;
CHECK(root.num_children() == 7);
CHECK(root["newseq"].num_children() == 0);
CHECK(root["newseq (serialized)"].num_children() == 0);
// adding a map node:
CHECK(root.num_children() == 7);
root["newmap"] |= ryml::MAP;
root.append_child() << ryml::key("newmap (serialized)") |= ryml::SEQ;
CHECK(root.num_children() == 9);
CHECK(root["newmap"].num_children() == 0);
CHECK(root["newmap (serialized)"].num_children() == 0);
// operator[] 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 do so if and when it is required.
//
// This is a significant difference from eg, the behavior of
// std::map, which mutates the map immediately within the call to
// operator[].
CHECK(!root.has_child("I am nobody"));
ryml::NodeRef nobody = root["I am nobody"];
CHECK(nobody.valid()); // points at the tree, and a specific place in the tree
CHECK(nobody.is_seed()); // ... but nothing is there yet.
CHECK(!root.has_child("I am nobody")); // same as above
ryml::NodeRef somebody = root["I am somebody"];
CHECK(!root.has_child("I am somebody")); // same as above
CHECK(somebody.valid());
CHECK(somebody.is_seed()); // same as above
somebody = "indeed"; // this will commit to the tree, mutating at the proper place
CHECK(somebody.valid());
CHECK(!somebody.is_seed()); // now the tree has this node, and it is no longer a seed
CHECK(root.has_child("I am somebody"));
CHECK(root["I am somebody"].val() == "indeed");
//------------------------------------------------------------------
// Emitting:
// emit to a FILE*
ryml::emit(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<std::string>(tree);
// can emit to any given buffer:
char buf[1024];
ryml::csubstr buf_result = ryml::emit(tree, buf);
// now check
ryml::csubstr expected_result = R"(foo: says who
bar:
- 20
- 30
- oh so nice
- oh so nice (serialized)
john: in_scope
newkeyval: shiny and new
newkeyval (serialized): shiny and new (serialized)
newseq: []
newseq (serialized): []
newmap: {}
newmap (serialized): []
I am somebody: indeed
)";
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.
//------------------------------------------------------------------
// Dealing with UTF8
ryml::Tree langs = ryml::parse_in_arena(R"(
en: Planet (Gas)
fr: Planète (Gazeuse)
ru: Планета (Газ)
ja: 惑星(ガス)
zh: 行星(气体)
decode this: "\u263A \xE2\x98\xBA"
and this as well: "\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):
CHECK(langs["decode this"].val() == "☺ ☺");
CHECK(langs["and this as well"].val() == "✅ 𝄞");
//------------------------------------------------------------------
// Getting the location of nodes in the source:
ryml::Parser parser;
ryml::Tree tree2 = parser.parse_in_arena("expected.yml", expected_result);
ryml::Location loc = parser.location(tree2["bar"][1]);
CHECK(parser.location_contents(loc).begins_with("30"));
CHECK(loc.line == 3u);
CHECK(loc.col == 4u);
// For further details in location tracking,
// refer to the sample function below.
}
//-----------------------------------------------------------------------------
/** demonstrate usage of ryml::substr/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 https://c4core.docsforge.com/master/api/c4/basic_substring/
* @see https://c4core.docsforge.com/master/api/c4/#substr
* @see https://c4core.docsforge.com/master/api/c4/#csubstr
*/
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);
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 a call to 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>.
// this was a deliberate design choice to avoid requiring
// 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);
CHECK(s.size() == s.len);
CHECK(s.data() == s.str);
}
// convert substr -> csubstr
{
char buf[] = "foo";
ryml::substr foo = buf;
CHECK(foo.len == 3);
CHECK(foo.data() == buf);
ryml::csubstr cfoo = foo;
CHECK(cfoo.data() == buf);
}
// cannot convert csubstr -> substr:
{
// ryml::substr foo2 = cfoo; // compile error: cannot write to csubstr
}
// construct from char[]/const char[]: mutable vs immutable memory
{
char const foobar_str_ro[] = "foobar"; // ro := read-only
char foobar_str_rw[] = "foobar"; // rw := read-write
static_assert(std::is_array<decltype(foobar_str_ro)>::value, "this is an array");
static_assert(std::is_array<decltype(foobar_str_rw)>::value, "this is an array");
// csubstr <- read-only memory
{
ryml::csubstr foobar = foobar_str_ro;
CHECK(foobar.data() == foobar_str_ro);
CHECK(foobar.size() == strlen(foobar_str_ro));
CHECK(foobar == "foobar"); // AKA strcmp
}
// csubstr <- read-write memory: you can create an immutable csubstr from mutable memory
{
ryml::csubstr foobar = foobar_str_rw;
CHECK(foobar.data() == foobar_str_rw);
CHECK(foobar.size() == strlen(foobar_str_rw));
CHECK(foobar == "foobar"); // AKA strcmp
}
// substr <- read-write memory.
{
ryml::substr foobar = foobar_str_rw;
CHECK(foobar.data() == foobar_str_rw);
CHECK(foobar.size() == strlen(foobar_str_rw));
CHECK(foobar == "foobar"); // AKA strcmp
}
// substr <- ro is impossible.
{
//ryml::substr foobar = foobar_str_ro; // compile error!
}
}
// construct from char*/const char*: mutable vs immutable memory.
// use to_substr()/to_csubstr()
{
char const* foobar_str_ro = "foobar"; // ro := read-only
char foobar_str_rw_[] = "foobar"; // rw := read-write
char * foobar_str_rw = foobar_str_rw_; // rw := read-write
static_assert(!std::is_array<decltype(foobar_str_ro)>::value, "this is a decayed pointer");
static_assert(!std::is_array<decltype(foobar_str_rw)>::value, "this is a decayed pointer");
// csubstr <- read-only memory
{
//ryml::csubstr foobar = foobar_str_ro; // compile error: length is not known
ryml::csubstr foobar = ryml::to_csubstr(foobar_str_ro);
CHECK(foobar.data() == foobar_str_ro);
CHECK(foobar.size() == strlen(foobar_str_ro));
CHECK(foobar == "foobar"); // AKA strcmp
}
// csubstr <- read-write memory: you can create an immutable csubstr from mutable memory
{
ryml::csubstr foobar = ryml::to_csubstr(foobar_str_rw);
CHECK(foobar.data() == foobar_str_rw);
CHECK(foobar.size() == strlen(foobar_str_rw));
CHECK(foobar == "foobar"); // AKA strcmp
}
// substr <- read-write memory.
{
ryml::substr foobar = ryml::to_substr(foobar_str_rw);
CHECK(foobar.data() == foobar_str_rw);
CHECK(foobar.size() == strlen(foobar_str_rw));
CHECK(foobar == "foobar"); // AKA strcmp
}
// substr <- read-only is impossible.
{
//ryml::substr foobar = ryml::to_substr(foobar_str_ro); // compile error!
}
}
// substr is mutable, without changing the size:
{
char buf[] = "foobar";
ryml::substr foobar = buf;
CHECK(foobar == "foobar");
foobar[0] = 'F'; CHECK(foobar == "Foobar");
foobar.back() = 'R'; CHECK(foobar == "FoobaR");
foobar.reverse(); CHECK(foobar == "RabooF");
foobar.reverse(); CHECK(foobar == "FoobaR");
foobar.reverse_sub(1, 4); CHECK(foobar == "FabooR");
foobar.reverse_sub(1, 4); CHECK(foobar == "FoobaR");
foobar.reverse_range(2, 5); CHECK(foobar == "FoaboR");
foobar.reverse_range(2, 5); CHECK(foobar == "FoobaR");
foobar.replace('o', '0'); CHECK(foobar == "F00baR");
foobar.replace('a', '_'); CHECK(foobar == "F00b_R");
foobar.replace("_0b", 'a'); CHECK(foobar == "FaaaaR");
foobar.toupper(); CHECK(foobar == "FAAAAR");
foobar.tolower(); CHECK(foobar == "faaaar");
foobar.fill('.'); CHECK(foobar == "......");
// see also:
// - .erase()
// - .replace_all()
}
// sub-views
{
ryml::csubstr s = "fooFOObarBAR";
CHECK(s.len == 12u);
// sub(): <- first,[num]
CHECK(s.sub(0) == "fooFOObarBAR");
CHECK(s.sub(0, 12) == "fooFOObarBAR");
CHECK(s.sub(0, 3) == "foo" );
CHECK(s.sub(3) == "FOObarBAR");
CHECK(s.sub(3, 3) == "FOO" );
CHECK(s.sub(6) == "barBAR");
CHECK(s.sub(6, 3) == "bar" );
CHECK(s.sub(9) == "BAR");
CHECK(s.sub(9, 3) == "BAR");
// first(): <- length
CHECK(s.first(0) == "" );
CHECK(s.first(1) == "f" );
CHECK(s.first(2) != "f" );
CHECK(s.first(2) == "fo" );
CHECK(s.first(3) == "foo");
// last(): <- length
CHECK(s.last(0) == "");
CHECK(s.last(1) == "R");
CHECK(s.last(2) == "AR");
CHECK(s.last(3) == "BAR");
// range(): <- first, last
CHECK(s.range(0, 12) == "fooFOObarBAR");
CHECK(s.range(1, 12) == "ooFOObarBAR");
CHECK(s.range(1, 11) == "ooFOObarBA" );
CHECK(s.range(2, 10) == "oFOObarB" );
CHECK(s.range(3, 9) == "FOObar" );
// offs(): offset from beginning, end
CHECK(s.offs(0, 0) == "fooFOObarBAR");
CHECK(s.offs(1, 0) == "ooFOObarBAR");
CHECK(s.offs(1, 1) == "ooFOObarBA" );
CHECK(s.offs(2, 1) == "oFOObarBA" );
CHECK(s.offs(2, 2) == "oFOObarB" );
CHECK(s.offs(3, 3) == "FOObar" );
// right_of(): <- pos, include_pos
CHECK(s.right_of(0, true) == "fooFOObarBAR");
CHECK(s.right_of(0, false) == "ooFOObarBAR");
CHECK(s.right_of(1, true) == "ooFOObarBAR");
CHECK(s.right_of(1, false) == "oFOObarBAR");
CHECK(s.right_of(2, true) == "oFOObarBAR");
CHECK(s.right_of(2, false) == "FOObarBAR");
CHECK(s.right_of(3, true) == "FOObarBAR");
CHECK(s.right_of(3, false) == "OObarBAR");
// left_of() <- pos, include_pos
CHECK(s.left_of(12, false) == "fooFOObarBAR");
CHECK(s.left_of(11, true) == "fooFOObarBAR");
CHECK(s.left_of(11, false) == "fooFOObarBA" );
CHECK(s.left_of(10, true) == "fooFOObarBA" );
CHECK(s.left_of(10, false) == "fooFOObarB" );
CHECK(s.left_of( 9, true) == "fooFOObarB" );
CHECK(s.left_of( 9, false) == "fooFOObar" );
// left_of(),right_of() <- substr
ryml::csubstr FOO = s.sub(3, 3);
CHECK(s.is_super(FOO)); // required for the following
CHECK(s.left_of(FOO) == "foo");
CHECK(s.right_of(FOO) == "barBAR");
}
// is_sub(),is_super()
{
ryml::csubstr foobar = "foobar";
ryml::csubstr foo = foobar.first(3);
CHECK(foo.is_sub(foobar));
CHECK(foo.is_sub(foo));
CHECK(!foo.is_super(foobar));
CHECK(!foobar.is_sub(foo));
// identity comparison is true:
CHECK(foo.is_super(foo));
CHECK(foo.is_sub(foo));
CHECK(foobar.is_sub(foobar));
CHECK(foobar.is_super(foobar));
}
// overlaps()
{
ryml::csubstr foobar = "foobar";
ryml::csubstr foo = foobar.first(3);
ryml::csubstr oba = foobar.offs(2, 1);
ryml::csubstr abc = "abc";
CHECK(foobar.overlaps(foo));
CHECK(foobar.overlaps(oba));
CHECK(foo.overlaps(foobar));
CHECK(foo.overlaps(oba));
CHECK(!foo.overlaps(abc));
CHECK(!abc.overlaps(foo));
}
// triml(): trim characters from the left
// trimr(): trim characters from the right
// trim(): trim characters from left AND right
{
CHECK(ryml::csubstr(" \t\n\rcontents without whitespace\t \n\r").trim("\t \n\r") == "contents without whitespace");
ryml::csubstr aaabbb = "aaabbb";
ryml::csubstr aaa___bbb = "aaa___bbb";
// trim a character:
CHECK(aaabbb.triml('a') == aaabbb.last(3)); // bbb
CHECK(aaabbb.trimr('a') == aaabbb);
CHECK(aaabbb.trim ('a') == aaabbb.last(3)); // bbb
CHECK(aaabbb.triml('b') == aaabbb);
CHECK(aaabbb.trimr('b') == aaabbb.first(3)); // aaa
CHECK(aaabbb.trim ('b') == aaabbb.first(3)); // aaa
CHECK(aaabbb.triml('c') == aaabbb);
CHECK(aaabbb.trimr('c') == aaabbb);
CHECK(aaabbb.trim ('c') == aaabbb);
CHECK(aaa___bbb.triml('a') == aaa___bbb.last(6)); // ___bbb
CHECK(aaa___bbb.trimr('a') == aaa___bbb);
CHECK(aaa___bbb.trim ('a') == aaa___bbb.last(6)); // ___bbb
CHECK(aaa___bbb.triml('b') == aaa___bbb);
CHECK(aaa___bbb.trimr('b') == aaa___bbb.first(6)); // aaa___
CHECK(aaa___bbb.trim ('b') == aaa___bbb.first(6)); // aaa___
CHECK(aaa___bbb.triml('c') == aaa___bbb);
CHECK(aaa___bbb.trimr('c') == aaa___bbb);
CHECK(aaa___bbb.trim ('c') == aaa___bbb);
// trim ANY of the characters:
CHECK(aaabbb.triml("ab") == "");
CHECK(aaabbb.trimr("ab") == "");
CHECK(aaabbb.trim ("ab") == "");
CHECK(aaabbb.triml("ba") == "");
CHECK(aaabbb.trimr("ba") == "");
CHECK(aaabbb.trim ("ba") == "");
CHECK(aaabbb.triml("cd") == aaabbb);
CHECK(aaabbb.trimr("cd") == aaabbb);
CHECK(aaabbb.trim ("cd") == aaabbb);
CHECK(aaa___bbb.triml("ab") == aaa___bbb.last(6)); // ___bbb
CHECK(aaa___bbb.triml("ba") == aaa___bbb.last(6)); // ___bbb
CHECK(aaa___bbb.triml("cd") == aaa___bbb);
CHECK(aaa___bbb.trimr("ab") == aaa___bbb.first(6)); // aaa___
CHECK(aaa___bbb.trimr("ba") == aaa___bbb.first(6)); // aaa___
CHECK(aaa___bbb.trimr("cd") == aaa___bbb);
CHECK(aaa___bbb.trim ("ab") == aaa___bbb.range(3, 6)); // ___
CHECK(aaa___bbb.trim ("ba") == aaa___bbb.range(3, 6)); // ___
CHECK(aaa___bbb.trim ("cd") == aaa___bbb);
}
// unquoted():
{
CHECK(ryml::csubstr(R"('this is is single quoted')").unquoted() == "this is is single quoted");
CHECK(ryml::csubstr(R"("this is is double quoted")").unquoted() == "this is is double quoted");
}
// stripl(): remove pattern from the left
// stripr(): remove pattern from the right
{
ryml::csubstr abc___cba = "abc___cba";
ryml::csubstr abc___abc = "abc___abc";
CHECK(abc___cba.stripl("abc") == abc___cba.last(6)); // ___cba
CHECK(abc___cba.stripr("abc") == abc___cba);
CHECK(abc___cba.stripl("ab") == abc___cba.last(7)); // c___cba
CHECK(abc___cba.stripr("ab") == abc___cba);
CHECK(abc___cba.stripl("a") == abc___cba.last(8)); // bc___cba, same as triml('a')
CHECK(abc___cba.stripr("a") == abc___cba.first(8));
CHECK(abc___abc.stripl("abc") == abc___abc.last(6)); // ___abc
CHECK(abc___abc.stripr("abc") == abc___abc.first(6)); // abc___
CHECK(abc___abc.stripl("ab") == abc___abc.last(7)); // c___cba
CHECK(abc___abc.stripr("ab") == abc___abc);
CHECK(abc___abc.stripl("a") == abc___abc.last(8)); // bc___cba, same as triml('a')
CHECK(abc___abc.stripr("a") == abc___abc);
}
// begins_with()/ends_with()
// begins_with_any()/ends_with_any()
{
ryml::csubstr s = "foobar123";
// char overloads
CHECK(s.begins_with('f'));
CHECK(s.ends_with('3'));
CHECK(!s.ends_with('2'));
CHECK(!s.ends_with('o'));
// char[] overloads
CHECK(s.begins_with("foobar"));
CHECK(s.begins_with("foo"));
CHECK(s.begins_with_any("foo"));
CHECK(!s.begins_with("oof"));
CHECK(s.begins_with_any("oof"));
CHECK(s.ends_with("23"));
CHECK(s.ends_with("123"));
CHECK(s.ends_with_any("123"));
CHECK(!s.ends_with("321"));
CHECK(s.ends_with_any("231"));
}
// select()
{
ryml::csubstr s = "0123456789";
CHECK(s.select('0') == s.sub(0, 1));
CHECK(s.select('1') == s.sub(1, 1));
CHECK(s.select('2') == s.sub(2, 1));
CHECK(s.select('8') == s.sub(8, 1));
CHECK(s.select('9') == s.sub(9, 1));
CHECK(s.select("0123") == s.range(0, 4));
CHECK(s.select("012" ) == s.range(0, 3));
CHECK(s.select("01" ) == s.range(0, 2));
CHECK(s.select("0" ) == s.range(0, 1));
CHECK(s.select( "123") == s.range(1, 4));
CHECK(s.select( "23") == s.range(2, 4));
CHECK(s.select( "3") == s.range(3, 4));
}
// find()
{
ryml::csubstr s012345 = "012345";
// find single characters:
CHECK(s012345.find('a') == ryml::npos);
CHECK(s012345.find('0' ) == 0u);
CHECK(s012345.find('0', 1u) == ryml::npos);
CHECK(s012345.find('1' ) == 1u);
CHECK(s012345.find('1', 2u) == ryml::npos);
CHECK(s012345.find('2' ) == 2u);
CHECK(s012345.find('2', 3u) == ryml::npos);
CHECK(s012345.find('3' ) == 3u);
CHECK(s012345.find('3', 4u) == ryml::npos);
// find patterns
CHECK(s012345.find("ab" ) == ryml::npos);
CHECK(s012345.find("01" ) == 0u);
CHECK(s012345.find("01", 1u) == ryml::npos);
CHECK(s012345.find("12" ) == 1u);
CHECK(s012345.find("12", 2u) == ryml::npos);
CHECK(s012345.find("23" ) == 2u);
CHECK(s012345.find("23", 3u) == ryml::npos);
}
// count(): count the number of occurrences of a character
{
ryml::csubstr buf = "00110022003300440055";
CHECK(buf.count('1' ) == 2u);
CHECK(buf.count('1', 0u) == 2u);
CHECK(buf.count('1', 1u) == 2u);
CHECK(buf.count('1', 2u) == 2u);
CHECK(buf.count('1', 3u) == 1u);
CHECK(buf.count('1', 4u) == 0u);
CHECK(buf.count('1', 5u) == 0u);
CHECK(buf.count('0' ) == 10u);
CHECK(buf.count('0', 0u) == 10u);
CHECK(buf.count('0', 1u) == 9u);
CHECK(buf.count('0', 2u) == 8u);
CHECK(buf.count('0', 3u) == 8u);
CHECK(buf.count('0', 4u) == 8u);
CHECK(buf.count('0', 5u) == 7u);
CHECK(buf.count('0', 6u) == 6u);
CHECK(buf.count('0', 7u) == 6u);
CHECK(buf.count('0', 8u) == 6u);
CHECK(buf.count('0', 9u) == 5u);
CHECK(buf.count('0', 10u) == 4u);
CHECK(buf.count('0', 11u) == 4u);
CHECK(buf.count('0', 12u) == 4u);
CHECK(buf.count('0', 13u) == 3u);
CHECK(buf.count('0', 14u) == 2u);
CHECK(buf.count('0', 15u) == 2u);
CHECK(buf.count('0', 16u) == 2u);
CHECK(buf.count('0', 17u) == 1u);
CHECK(buf.count('0', 18u) == 0u);
CHECK(buf.count('0', 19u) == 0u);
CHECK(buf.count('0', 20u) == 0u);
}
// first_of(),last_of()
{
ryml::csubstr s012345 = "012345";
CHECK(s012345.first_of('a') == ryml::npos);
CHECK(s012345.first_of("ab") == ryml::npos);
CHECK(s012345.first_of('0') == 0u);
CHECK(s012345.first_of("0") == 0u);
CHECK(s012345.first_of("01") == 0u);
CHECK(s012345.first_of("10") == 0u);
CHECK(s012345.first_of("012") == 0u);
CHECK(s012345.first_of("210") == 0u);
CHECK(s012345.first_of("0123") == 0u);