/
serialisation.d
1046 lines (910 loc) · 27.3 KB
/
serialisation.d
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
/++
+ Various functions related to serialising and deserialising structs into/from
+ .ini-like files.
+
+ Example:
+ ---
+ struct FooSettings
+ {
+ string fooasdf;
+ string bar;
+ string bazzzzzzz;
+ @Quoted flerrp;
+ double pi;
+ }
+
+ FooSettings f;
+
+ f.fooasdf = "foo";
+ f.bar = "bar";
+ f.bazzzzzzz = "baz";
+ f.flerrp = "hirr steff ";
+ f.pi = 3.14159;
+
+ enum fooSerialised =
+ `[Foo]
+ fooasdf foo
+ bar bar
+ bazzzzzzz baz
+ flerrp "hirr steff "
+ pi 3.14159`;
+
+ enum fooJustified =
+ `[Foo]
+ fooasdf foo
+ bar bar
+ bazzzzzzz baz
+ flerrp "hirr steff "
+ pi 3.14159`;
+
+ Appender!string sink;
+
+ sink.serialise(f);
+ assert(sink.data.justifiedEntryValueText == fooJustified);
+
+ FooSettings mirror;
+ deserialise(fooSerialised, mirror);
+ assert(mirror == f);
+
+ FooSettings mirror2;
+ deserialise(fooJustified, mirror2);
+ assert(mirror2 == mirror);
+ ---
+/
module lu.serialisation;
private:
import lu.traits : isStruct;
import std.meta : allSatisfy;
import std.range.primitives : isOutputRange;
import std.typecons : Flag, No, Yes;
public:
// serialise
/++
+ Convenience function to call `serialise` on several objects.
+
+ Example:
+ ---
+ struct Foo
+ {
+ // ...
+ }
+
+ struct Bar
+ {
+ // ...
+ }
+
+ Foo foo;
+ Bar bar;
+
+ Appender!string sink;
+
+ sink.serialise(foo, bar);
+ assert(!sink.data.empty);
+ ---
+
+ Params:
+ sink = Reference output range to write the serialised objects to (in
+ their .ini file-like format).
+ things = Variadic list of objects to serialise.
+/
void serialise(Sink, Things...)(auto ref Sink sink, Things things)
if ((Things.length > 1) && isOutputRange!(Sink, char[]))
{
foreach (immutable i, const thing; things)
{
if (i > 0) sink.put('\n');
sink.serialise(thing);
}
}
// serialise
/++
+ Serialises the fields of an object into an .ini file-like format.
+
+ It only serialises fields not annotated with `lu.uda.Unserialisable`,
+ and it doesn't recurse into other structs or classes.
+
+ Example:
+ ---
+ struct Foo
+ {
+ // ...
+ }
+
+ Foo foo;
+
+ Appender!string sink;
+
+ sink.serialise(foo);
+ assert(!sink.data.empty);
+ ---
+
+ Params:
+ sink = Reference output range to write to, usually an `std.array.Appender!string`.
+ thing = Object to serialise.
+/
void serialise(Sink, QualThing)(auto ref Sink sink, QualThing thing)
if (isOutputRange!(Sink, char[]))
{
import lu.string : stripSuffix;
import std.format : format, formattedWrite;
import std.traits : Unqual;
static if (!__traits(hasMember, Sink, "put")) import std.range.primitives : put;
static if (__traits(hasMember, Sink, "data"))
{
// Sink is not empty, place a newline between current content and new
if (sink.data.length) sink.put("\n");
}
alias Thing = Unqual!QualThing;
sink.formattedWrite("[%s]\n", Thing.stringof.stripSuffix("Settings"));
foreach (immutable i, member; thing.tupleof)
{
import lu.traits : isAnnotated, isSerialisable;
import lu.uda : Separator, Unserialisable;
alias T = Unqual!(typeof(member));
static if (
isSerialisable!member &&
!isAnnotated!(thing.tupleof[i], Unserialisable) &&
!is(T == struct) && !is(T == class))
{
import std.traits : isArray, isSomeString;
enum memberstring = __traits(identifier, thing.tupleof[i]);
static if (!isSomeString!T && isArray!T)
{
import std.traits : getUDAs, hasUDA;
// array, join it together
static if (hasUDA!(thing.tupleof[i], Separator))
{
alias separators = getUDAs!(thing.tupleof[i], Separator);
enum separator = separators[0].token;
static assert(separator.length, ("`%s.%s` is annotated with an " ~
"invalid `Separator` (empty)")
.format(Thing.stringof, memberstring));
}
else static if ((__VERSION__ >= 2087L) && hasUDA!(thing.tupleof[i], string))
{
alias separators = getUDAs!(thing.tupleof[i], string);
enum separator = separators[0];
static assert(separator.length, ("`%s.%s` is annotated with an " ~
"empty separator string")
.format(Thing.stringof, memberstring));
}
else
{
static assert (0, "`%s.%s` is not annotated with a `Separator`"
.format(Thing.stringof, memberstring));
}
enum arrayPattern = "%-(%s" ~ separator ~ "%)";
static if (is(typeof(member) == string[]))
{
string value;
if (member.length)
{
import std.algorithm.iteration : map;
import std.array : replace;
enum escaped = '\\' ~ separator;
enum placeholder = "\0\0"; // anything really
// Replace separators with a placeholder and flatten with format
auto separatedElements = member.map!(a => a.replace(separator, placeholder));
value = arrayPattern
.format(separatedElements)
.replace(placeholder, escaped);
static if (separators.length > 1)
{
foreach (immutable furtherSeparator; separators[1..$])
{
// We're serialising; escape any other separators
enum furtherEscaped = '\\' ~ furtherSeparator.token;
value = value.replace(furtherSeparator.token, furtherEscaped);
}
}
}
}
else
{
immutable value = arrayPattern.format(member);
}
}
else static if (is(T == enum))
{
import lu.conv : Enum;
immutable value = Enum!T.toString(member);
}
else
{
immutable value = member;
}
import std.range : hasLength;
static if (is(T == bool) || is(T == enum))
{
enum comment = false;
}
else static if (is(T == float) || is(T == double))
{
import std.conv : to;
import std.math : isNaN;
immutable comment = member.to!T.isNaN;
}
else static if (hasLength!T || isSomeString!T)
{
immutable comment = !member.length;
}
else
{
immutable comment = (member == T.init);
}
if (i > 0) sink.put('\n');
if (comment)
{
// .init or otherwise disabled
//sink.formattedWrite("#%s", memberstring);
sink.put('#');
sink.put(memberstring);
}
else
{
import lu.uda : Quoted;
static if (isSomeString!T && isAnnotated!(thing.tupleof[i], Quoted))
{
sink.formattedWrite("%s \"%s\"", memberstring, value);
}
else
{
sink.formattedWrite("%s %s", memberstring, value);
}
}
}
}
static if (!__traits(hasMember, Sink, "data"))
{
// Not an Appender, may be stdout.lockingTextWriter
sink.put('\n');
}
}
///
unittest
{
import lu.uda : Separator, Quoted;
import std.array : Appender;
struct FooSettings
{
string fooasdf = "foo 1";
string bar = "foo 1";
string bazzzzzzz = "foo 1";
@Quoted flerrp = "hirr steff ";
double pi = 3.14159;
@Separator(",") arr = [ 1, 2, 3 ];
static if (__VERSION__ >= 2087L)
{
@("|") matey = [ "a", "b", "c" ];
}
}
struct BarSettings
{
string foofdsa = "foo 2";
string bar = "bar 2";
string bazyyyyyyy = "baz 2";
@Quoted flarrp = " hirrsteff";
double pipyon = 3.0;
}
static if (__VERSION__ >= 2087L)
{
enum fooSerialised =
`[Foo]
fooasdf foo 1
bar foo 1
bazzzzzzz foo 1
flerrp "hirr steff "
pi 3.14159
arr 1,2,3
matey a|b|c`;
}
else
{
enum fooSerialised =
`[Foo]
fooasdf foo 1
bar foo 1
bazzzzzzz foo 1
flerrp "hirr steff "
pi 3.14159
arr 1,2,3`;
}
Appender!string fooSink;
fooSink.reserve(64);
fooSink.serialise(FooSettings.init);
assert((fooSink.data == fooSerialised), '\n' ~ fooSink.data);
enum barSerialised =
`[Bar]
foofdsa foo 2
bar bar 2
bazyyyyyyy baz 2
flarrp " hirrsteff"
pipyon 3`;
Appender!string barSink;
barSink.reserve(64);
barSink.serialise(BarSettings.init);
assert((barSink.data == barSerialised), '\n' ~ barSink.data);
// try two at once
Appender!string bothSink;
bothSink.reserve(128);
bothSink.serialise(FooSettings.init, BarSettings.init);
assert(bothSink.data == fooSink.data ~ "\n\n" ~ barSink.data);
}
@safe:
// deserialise
/++
+ Takes an input range containing serialised entry-value text and applies the
+ contents therein to one or more passed struct/class objects.
+
+ Example:
+ ---
+ struct Foo
+ {
+ // ...
+ }
+
+ struct Bar
+ {
+ // ...
+ }
+
+ Foo foo;
+ Bar bar;
+
+ string[][string] missingEntries;
+ string[][string] invalidEntries;
+
+ string fromFile = readText("configuration.conf");
+
+ fromFile
+ .splitter("\n")
+ .deserialise(missingEntries, invalidEntries, foo, bar);
+ ---
+
+ Params:
+ range = Input range from which to read the serialised text.
+ missingEntries = Out reference of an associative array of string arrays
+ of expected entries that were missing.
+ invalidEntries = Out reference of an associative array of string arrays
+ of unexpected entries that did not belong.
+ things = Reference variadic list of one or more objects to apply the
+ deserialised values to.
+
+ Throws: `DeserialisationException` if there were bad lines.
+/
void deserialise(Range, Things...)(Range range, out string[][string] missingEntries,
out string[][string] invalidEntries, ref Things things) pure
if (allSatisfy!(isStruct, Things))
{
import lu.string : stripSuffix, stripped;
import lu.traits : isAnnotated, isSerialisable;
import lu.uda : Unserialisable;
import std.format : format;
string section;
bool[Things.length] processedThings;
bool[string][string] encounteredOptions;
// Populate `encounteredOptions` with all the options in `Things`, but
// set them to false. Flip to true when we encounter one.
foreach (immutable i, thing; things)
{
alias Thing = typeof(thing);
static foreach (immutable n; 0..things[i].tupleof.length)
{{
static if (isSerialisable!(Things[i].tupleof[n]) &&
!isAnnotated!(things[i].tupleof[n], Unserialisable))
{
enum memberstring = __traits(identifier, Things[i].tupleof[n]);
encounteredOptions[Thing.stringof][memberstring] = false;
}
}}
}
lineloop:
foreach (const rawline; range)
{
string line = rawline.stripped; // mutable
if (!line.length) continue;
bool commented;
switch (line[0])
{
case '#':
case ';':
// Comment
if (!section.length) continue; // e.g. banner
while (line.length && ((line[0] == '#') || (line[0] == ';') || (line[0] == '/')))
{
line = line[1..$];
}
if (!line.length) continue;
commented = true;
goto default;
case '/':
if ((line.length > 1) && (line[1] == '/'))
{
// Also a comment; //
continue;
}
goto default;
case '[':
// New section. Check if there's still something to do
immutable sectionBackup = line;
bool stillSomethingToProcess;
static foreach (immutable size_t i; 0..Things.length)
{
stillSomethingToProcess |= !processedThings[i];
}
if (!stillSomethingToProcess) break lineloop; // All done, early break
try
{
import std.format : formattedRead;
line.formattedRead("[%s]", section);
}
catch (Exception e)
{
throw new DeserialisationException("Malformed section header \"%s\", %s"
.format(sectionBackup, e.msg));
}
continue;
default:
// entry-value line
if (!section.length)
{
throw new DeserialisationException("Sectionless orphan \"%s\""
.format(line));
}
thingloop:
foreach (immutable i, thing; things)
{
import lu.traits : isSerialisable;
import lu.uda : CannotContainComments;
import std.traits : Unqual;
alias T = Unqual!(typeof(thing));
enum settingslessT = T.stringof.stripSuffix("Settings").idup;
if (section != settingslessT) continue thingloop;
processedThings[i] = true;
immutable result = splitEntryValue(line);
immutable entry = result.entry;
if (!entry.length) continue;
string value = result.value; // mutable for later slicing
switch (entry)
{
static foreach (immutable n; 0..things[i].tupleof.length)
{{
static if (isSerialisable!(Things[i].tupleof[n]) &&
!isAnnotated!(things[i].tupleof[n], Unserialisable))
{
enum memberstring = __traits(identifier, Things[i].tupleof[n]);
case memberstring:
import lu.objmanip : setMemberByName;
if (!commented)
{
// Entry is uncommented; set
static if (isAnnotated!(things[i].tupleof[n], CannotContainComments))
{
things[i].setMemberByName(entry, value);
}
else
{
import lu.string : contains, nom;
// Slice away any comments
value = value.contains('#') ? value.nom('#') : value;
value = value.contains(';') ? value.nom(';') : value;
value = value.contains("//") ? value.nom("//") : value;
things[i].setMemberByName(entry, value);
}
}
encounteredOptions[Things[i].stringof][memberstring] = true;
continue lineloop;
}
}}
default:
// Unknown setting in known section
if (!commented) invalidEntries[section] ~= entry.length ? entry : line;
break;
}
}
break;
}
}
// Compose missing entries and save them as arrays in `missingEntries`.
foreach (immutable encounteredSection, const entryMatches; encounteredOptions)
{
foreach (immutable entry, immutable encountered; entryMatches)
{
immutable sectionName = encounteredSection.stripSuffix("Settings");
if (!encountered) missingEntries[sectionName] ~= entry;
}
}
}
///
unittest
{
import lu.uda : Separator;
import std.algorithm.iteration : splitter;
import std.conv : text;
struct FooSettings
{
enum Bar { blaawp = 5, oorgle = -1 }
int i;
string s;
bool b;
float f;
double d;
Bar bar;
string omitted;
@Separator(",")
{
int[] ia;
string[] sa;
bool[] ba;
float[] fa;
double[] da;
Bar[] bara;
}
}
enum serialisedFileContents = `
[Foo]
i 42
ia 1,2,-3,4,5
s hello world!
sa hello,world,!
b true
ba true,false,true
wrong name
# comment
; other type of comment
// third type of comment
f 3.14 #hirp
fa 0.0,1.1,-2.2,3.3 ;herp
d 99.9 //derp
da 99.9999,0.0001,-1
bar oorgle
bara blaawp,oorgle,blaawp
[DifferentSection]
ignored completely
because no DifferentSection struct was passed
nil 5
naN !"¤%&/`;
string[][string] missing;
string[][string] invalid;
FooSettings foo;
serialisedFileContents
.splitter("\n")
.deserialise(missing, invalid, foo);
with (foo)
{
assert((i == 42), i.text);
assert((ia == [ 1, 2, -3, 4, 5 ]), ia.text);
assert((s == "hello world!"), s);
assert((sa == [ "hello", "world", "!" ]), sa.text);
assert(b);
assert((ba == [ true, false, true ]), ba.text);
assert((f == 3.14f), f.text);
assert((fa == [ 0.0f, 1.1f, -2.2f, 3.3f ]), fa.text);
assert((d == 99.9), d.text);
// rounding errors with LDC on Windows
import std.math : approxEqual;
assert(da[0].approxEqual(99.9999), da[0].text);
assert(da[1].approxEqual(0.0001), da[1].text);
assert(da[2].approxEqual(-1.0), da[2].text);
with (FooSettings.Bar)
{
assert((bar == oorgle), b.text);
assert((bara == [ blaawp, oorgle, blaawp ]), bara.text);
}
}
import std.algorithm.searching : canFind;
assert("Foo" in missing);
assert(missing["Foo"].canFind("omitted"));
assert("Foo" in invalid);
assert(invalid["Foo"].canFind("wrong"));
struct DifferentSection
{
string ignored;
string because;
int nil;
string naN;
}
// Can read other structs from the same file
DifferentSection diff;
serialisedFileContents
.splitter("\n")
.deserialise(missing, invalid, diff);
with (diff)
{
assert((ignored == "completely"), ignored);
assert((because == "no DifferentSection struct was passed"), because);
assert((nil == 5), nil.text);
assert((naN == `!"¤%&/`), naN);
}
}
// justifiedEntryValueText
/++
+ Takes an unformatted string of serialised entry-value text and justifies it
+ intto two neat columns.
+
+ It does one pass through it all first to determine the maximum width of the
+ entry names, then another to format it and eventually return a flat string.
+
+ Example:
+ ---
+ struct Foo
+ {
+ // ...
+ }
+
+ struct Bar
+ {
+ // ...
+ }
+
+ Foo foo;
+ Bar bar;
+
+ Appender!string sink;
+
+ sink.serialise(foo, bar);
+ immutable justified = sink.data.justifiedEntryValueText;
+ ---
+
+ Params:
+ origLines = Unjustified raw serialised text.
+
+ Returns:
+ .ini file-like text, justified into two columns.
+/
auto justifiedEntryValueText(const string origLines) pure
{
import lu.string : stripped;
import std.algorithm.comparison : max;
import std.algorithm.iteration : splitter;
import std.array : Appender;
enum decentReserve = 4096;
Appender!(string[]) unjustified;
unjustified.reserve(decentReserve);
size_t longestEntryLength;
foreach (immutable rawline; origLines.splitter("\n"))
{
immutable line = rawline.stripped;
if (!line.length)
{
unjustified.put("");
continue;
}
switch (line[0])
{
case '#':
case ';':
case '[':
// comment or section header
unjustified.put(line);
continue;
case '/':
if ((line.length > 1) && (line[1] == '/'))
{
// Also a comment
goto case '#';
}
goto default;
default:
import std.format : format;
immutable result = splitEntryValue(line);
longestEntryLength = max(longestEntryLength, result.entry.length);
unjustified.put("%s %s".format(result.entry, result.value));
break;
}
}
import lu.numeric : getMultipleOf;
import std.algorithm.iteration : joiner;
Appender!string justified;
justified.reserve(decentReserve);
assert((longestEntryLength > 0), "No longest entry; is the struct empty?");
assert((unjustified.data.length > 0), "Unjustified data is empty");
enum minimumWidth = 24;
immutable width = max(minimumWidth, longestEntryLength.getMultipleOf!(Yes.alwaysOneUp)(4));
foreach (immutable i, immutable line; unjustified.data)
{
if (!line.length)
{
// Don't add a linebreak at the top of the file
if (justified.data.length) justified.put("\n");
continue;
}
if (i > 0) justified.put('\n');
switch (line[0])
{
case '#':
case ';':
case '[':
justified.put(line);
continue;
case '/':
if ((line.length > 1) && (line[1] == '/'))
{
// Also a comment
goto case '#';
}
goto default;
default:
import std.format : formattedWrite;
immutable result = splitEntryValue(line);
justified.formattedWrite("%-*s%s", width, result.entry, result.value);
break;
}
}
return justified.data;
}
unittest
{
import std.algorithm.iteration : splitter;
import std.array : Appender;
import lu.uda : Separator;
struct Foo
{
enum Bar { blaawp = 5, oorgle = -1 }
int someInt = 42;
string someString = "hello world!";
bool someBool = true;
float someFloat = 3.14f;
double someDouble = 99.9;
Bar someBars = Bar.oorgle;
string harbl;
@Separator(",")
{
int[] intArray = [ 1, 2, -3, 4, 5 ];
string[] stringArrayy = [ "hello", "world", "!" ];
bool[] boolArray = [ true, false, true ];
float[] floatArray = [ 0.0, 1.1, -2.2, 3.3 ];
double[] doubleArray = [ 99.9999, 0.0001, -1.0 ];
Bar[] barArray = [ Bar.blaawp, Bar.oorgle, Bar.blaawp ];
string[] yarn;
}
}
struct DifferentSection
{
string ignored = "completely";
string because = " no DifferentSection struct was passed";
int nil = 5;
string naN = `!"#¤%&/`;
}
Appender!string sink;
sink.reserve(512);
Foo foo;
DifferentSection diff;
enum unjustified =
`[Foo]
someInt 42
someString hello world!
someBool true
someFloat 3.14
someDouble 99.9
someBars oorgle
#harbl
intArray 1,2,-3,4,5
stringArrayy hello,world,!
boolArray true,false,true
floatArray 0,1.1,-2.2,3.3
doubleArray 99.9999,0.0001,-1
barArray blaawp,oorgle,blaawp
#yarn
[DifferentSection]
ignored completely
because no DifferentSection struct was passed
nil 5
naN !"#¤%&/`;
enum justified =
`[Foo]
someInt 42
someString hello world!
someBool true
someFloat 3.14
someDouble 99.9
someBars oorgle
#harbl
intArray 1,2,-3,4,5
stringArrayy hello,world,!
boolArray true,false,true
floatArray 0,1.1,-2.2,3.3
doubleArray 99.9999,0.0001,-1
barArray blaawp,oorgle,blaawp
#yarn
[DifferentSection]
ignored completely
because no DifferentSection struct was passed
nil 5
naN !"#¤%&/`;
sink.serialise(foo, diff);
assert((sink.data == unjustified), '\n' ~ sink.data);
immutable configText = justifiedEntryValueText(sink.data);
assert((configText == justified), '\n' ~ configText);
}
// DeserialisationException
/++
+ Exception, to be thrown when the specified serialised text could not be
+ parsed, for whatever reason.
+/
final class DeserialisationException : Exception
{
@safe:
/++
+ Create a new `DeserialisationException`.
+/
this(const string message, const string file = __FILE__, const size_t line = __LINE__) pure nothrow @nogc
{
super(message, file, line);
}
}
// splitEntryValue
/++
+ Splits a line into an entry and a value component.
+
+ This drop-in-replaces the regex: `"^(?P<entry>[^ \t]+)[ \t]+(?P<value>.+)"`.
+
+ Params:
+ line = String to split up.
+
+ Returns:
+ A Voldemort struct with an `entry` and a `value` member.
+/
auto splitEntryValue(const string line) pure nothrow @nogc
{
import std.string : representation;
import std.ascii : isWhite;
struct EntryValue
{
string entry;
string value;
}
EntryValue result;
foreach (immutable i, immutable c; line.representation)
{
if (!c.isWhite)
{
if (result.entry.length)
{
result.value = line[i..$];
break;
}