/
util.d
1679 lines (1453 loc) · 53.6 KB
/
util.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
// Written in the D programming language
/++
This module contains helper functions which aren't specific to the parser,
the DOM, or the writer.
$(TABLE
$(TR $(TH Symbol) $(TH Description))
$(TR $(TD $(LREF decodeXML))
$(TD Takes a range of characters, strips carriage returns from it,
and converts both character references and the predefined
entity references in the range into the characters that they
refer to.))
$(TR $(TD $(LREF asDecodedXML))
$(TD The version of $(LREF decodeXML) that returns a lazy range.))
$(TR $(TD $(LREF parseCharRef))
$(TD Parses a character reference from the front of a range of
characters.))
$(TR $(TD $(LREF parseStdEntityRef))
$(TD Parses one of the predefined entity references from the start
of a range of characters.))
$(TR $(TD $(LREF stripIndent))
$(TD Removes the indent from the front of each line of a range of
characters that was XML text which was formatted for
human-readability.))
$(TR $(TD $(LREF withoutIndent))
$(TD The version of $(LREF stripIndent) that returns a lazy
range.))
$(TR $(TD $(LREF StdEntityRef))
$(TD Enum containing the string representations of the five,
predefined entity references.))
$(TR $(TD $(LREF encodeText))
$(TD Encodes characters which cannot appear in
$(REF_ALTTEXT EntityType.text, EntityType.text, dxml, parser)
in their literal form.))
$(TR $(TD $(LREF encodeAttr))
$(TD Encodes characters which cannot appear in the attribute value
of an element start tag in their literal form.))
$(TR $(TD $(LREF encodeCharRef))
$(TD Encodes a character as a character reference.))
)
Copyright: Copyright 2018
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTPS jmdavisprog.com, Jonathan M Davis)
Source: $(LINK_TO_SRC dxml/_util.d)
See_Also: $(LINK2 http://www.w3.org/TR/REC-xml/, Official Specification for XML 1.0)
+/
module dxml.util;
import std.range.primitives;
import std.traits;
import std.typecons : Nullable;
/++
Decodes any XML character references and standard XML entity references in
the text as well as removing any carriage returns. It's intended to be used
on the text fields of element tags and on the values of start tag
attributes.
There are a number of characters that either can't be directly represented
in the text fields or attribute values in XML or which can sometimes be
directly represented but not always (e.g. an attribute value can contain
either a single quote or a double quote, but it can't contain both at the
same time, because one of them would match the opening quote). So, those
characters have alternate representations in order to be allowed (e.g.
$(D_CODE_STRING "$(AMP)lt;") for $(D_CODE_STRING '<'), because
$(D_CODE_STRING '<') would normally be the beginning of an entity).
Technically, they're entity references, but the ones handled by decodeXML
are the ones explicitly defined in the XML standard and which don't require
a DTD section.
Ideally, the parser would transform all such alternate representations to
what they represent when providing the text to the application, but that
would make it impossible to return slices of the original text from the
properties of an $(REF_ALTTEXT Entity, EntityRange.Entity, dxml, parser).
So, instead of having those properties do the transformation themselves,
decodeXML and asDecodedXML do that so that the application can choose to do
it or not (in many cases, there is nothing to decode, making the calls
unnecessary).
Similarly, an application can choose to encode a character as a character
reference (e.g. $(D_CODE_STRING '$(AMP)#65") or
$(D_CODE_STRING '$(AMP)#x40") for $(D_CODE_STRING 'A')). decodeXML will
decode such character references to their corresponding characters.
However, decodeXML does not handle any entity references beyond the five
predefined ones listed below. All others are left unprocessed. Processing
them properly would require handling the DTD section, which dxml does not
support. The parser considers any entity references other than the
predefined ones to be invalid XML, so unless the text being passed to
decodeXML doesn't come from dxml's parser, it can't have any entity
references in it other than the predefined ones. Similarly, invalid
character references are left unprocessed as well as any character that is
not valid in an XML document. decodeXML never throws on invalid XML.
Also, $(D_CODE_STRING '\r') is not supposed to appear in an XML document
except as a character reference unless it's in a CDATA section. So, it
really should be stripped out before being handed off to the application,
but again, that doesn't work with slices. So, decodeXML also handles that.
Specifically, what decodeXML and asDecodedXML do is
$(TABLE
$(TR $(TD convert $(D_CODE_STRING $(AMP)amp;) to $(D_CODE_STRING &)))
$(TR $(TD convert $(D_CODE_STRING $(AMP)gt;) to $(D_CODE_STRING >)))
$(TR $(TD convert $(D_CODE_STRING $(AMP)lt;) to $(D_CODE_STRING <)))
$(TR $(TD convert $(D_CODE_STRING $(AMP)apos;) to $(D_CODE_STRING ')))
$(TR $(TD convert $(D_CODE_STRING $(AMP)quot;) to $(D_CODE_STRING ")))
$(TR $(TD remove all instances of $(D_CODE_STRING \r)))
$(TR $(TD convert all character references (e.g.
$(D_CODE_STRING $(AMP)#xA;)) to the characters that they
represent))
)
All other entity references are left untouched, and any $(D_CODE_STRING '&')
which is not used in one of the constructs listed in the table as well as
any malformed constructs (e.g. $(D_CODE_STRING "&Amp;") or
$(D_CODE_STRING "&#xGGA2;")) are left untouched.
The difference between decodeXML and asDecodedXML is that decodeXML returns
a $(K_STRING), whereas asDecodedXML returns a lazy _range of code
units. In the case where a $(K_STRING) is passed to decodeXML, it
will simply return the original $(K_STRING) if there is no text to decode
(whereas in other cases, decodeXML and asDecodedXML are forced to return
new ranges even if there is no text to decode).
Params:
range = The _range of characters to decodeXML.
Returns: The decoded text. decodeXML returns a $(K_STRING), whereas
asDecodedXML returns a lazy _range of code units (so it could be a
_range of $(K_CHAR) or $(K_WCHAR) and not just $(K_DCHAR); which it
is depends on the code units of the _range being passed in).
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#dt-chardata)$(BR)
$(LREF parseStdEntityRef)$(BR)
$(LREF parseCharRef)$(BR)
$(REF EntityRange.Entity.attributes, dxml, parser)$(BR)
$(REF EntityRange.Entity.text, dxml, parser)$(BR)
$(LREF encodeAttr)$(BR)
$(LREF encodeText)
+/
string decodeXML(R)(R range)
if(isForwardRange!R && isSomeChar!(ElementType!R))
{
static if(isDynamicArray!R && is(Unqual!(ElementEncodingType!R) == char))
{
import std.algorithm.searching : find, startsWith;
import std.array : appender;
import std.meta : AliasSeq;
auto found = range.find('&', '\r');
if(found[1] == 0)
return range;
auto retval = appender!string();
retval.reserve(range.length);
put(retval, range[0 .. $ - found[0].length]);
range = range[$ - found[0].length .. $];
size_t i = 0;
loop: for(; i != range.length;)
{
switch(range[i])
{
case '&':
{
if(i + 1 == range.length)
{
++i;
break loop;
}
put(retval, range[0 .. i]);
range = range[i .. $];
i = 0;
static foreach(func; AliasSeq!(parseStdEntityRef, parseCharRef))
{{
immutable c = func(range);
if(!c.isNull)
{
put(retval, c.get);
continue loop;
}
}}
put(retval, '&');
range = range[1 .. $];
continue;
}
case '\r':
{
if(i != 0)
{
put(retval, range[0 .. i]);
range = range[i + 1 .. $];
i = 0;
}
else
range = range[1 .. $];
continue;
}
default: ++i; continue;
}
}
if(i != 0)
put(retval, range[0 .. i]);
return retval.data;
}
else
{
import std.conv : to;
return range.asDecodedXML().to!string();
}
}
/// Ditto
auto asDecodedXML(R)(R range)
if(isForwardRange!R && isSomeChar!(ElementType!R))
{
import std.meta : AliasSeq;
import std.utf : byCodeUnit, encode, UseReplacementDchar;
static struct DecodedXML
{
public:
@property empty() { return _range.empty && _begin == _end; }
void popFront()
{
if(_begin != _end)
{
if(++_begin != _end)
return;
}
else
_range.popFront();
_popFrontImpl();
}
@property save()
{
auto retval = this;
retval._range = _range.save;
return retval;
}
private:
void _popFrontImpl()
{
while(!_range.empty)
{
switch(_range.front)
{
case '&':
{
static foreach(func; AliasSeq!(parseStdEntityRef, parseCharRef))
{{
immutable c = func(_range);
if(!c.isNull)
{
_begin = 0;
_end = _buffer.encode!(UseReplacementDchar.yes)(c);
return;
}
}}
goto default;
}
case '\r':
{
assert(_begin == _end);
_range.popFront();
continue;
}
default:
{
assert(_begin == _end);
return;
}
}
}
}
this(R range) @safe
{
_range = byCodeUnit(range);
_popFrontImpl();
}
typeof(byCodeUnit(R.init)) _range;
static if(is(Unqual!(ElementEncodingType!R) == char))
char[4] _buffer;
else static if(is(Unqual!(ElementEncodingType!R) == wchar))
wchar[2] _buffer;
else
dchar[1] _buffer;
size_t _begin;
size_t _end;
public:
// FIXME A compiler bug prevents this from going with the public declarations
// above. If it's there, the compiler thinks that _buffer isn't defined when
// it tries to compile front. It needs to be reduced and reported.
@property typeof(_buffer[0]) front() { return _begin == _end ? _range.front : _buffer[_begin]; }
}
return DecodedXML(range);
}
///
version(dxmlTests) unittest
{
assert(decodeXML("hello world &><'" \r\r\r\r\r foo") ==
`hello world &><'" foo`);
assert(decodeXML("if(foo && bar)\r\n" ~
" left = right;") ==
"if(foo && bar)\n" ~
" left = right;");
assert(decodeXML("ディラン") == "ディラン");
assert(decodeXML("foo") == "foo");
assert(decodeXML("&# ;") == "&# ;");
{
import std.algorithm.comparison : equal;
auto range = asDecodedXML("hello world &><'" " ~
"\r\r\r\r\r foo");
assert(equal(range, `hello world &><'" foo`));
}
{
import dxml.parser;
auto xml = "<root>\n" ~
" <function return='vector<int>' name='foo'>\r\n" ~
" <doc_comment>This function does something really\r\n" ~
" fancy, and you will love it.</doc_comment>\r\n" ~
" <param type='int' name='i'>\r\n" ~
" <param type='const std::string&' name='s'>\r\n" ~
" </function>\n" ~
"</root>";
auto range = parseXML!simpleXML(xml);
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "function");
{
auto attrs = range.front.attributes;
assert(attrs.front.name == "return");
assert(attrs.front.value == "vector<int>");
assert(decodeXML(attrs.front.value) == "vector<int>");
attrs.popFront();
assert(attrs.front.name == "name");
assert(attrs.front.value == "foo");
assert(decodeXML(attrs.front.value) == "foo");
}
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "doc_comment");
range.popFront();
assert(range.front.text ==
"This function does something really\r\n" ~
" fancy, and you will love it.");
assert(decodeXML(range.front.text) ==
"This function does something really\n" ~
" fancy, and you will love it.");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "doc_comment");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "param");
{
auto attrs = range.front.attributes;
assert(attrs.front.name == "type");
assert(attrs.front.value == "int");
assert(decodeXML(attrs.front.value) == "int");
attrs.popFront();
assert(attrs.front.name == "name");
assert(attrs.front.value == "i");
assert(decodeXML(attrs.front.value) == "i");
}
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "param");
{
auto attrs = range.front.attributes;
assert(attrs.front.name == "type");
assert(attrs.front.value == "const std::string&");
assert(decodeXML(attrs.front.value) == "const std::string&");
attrs.popFront();
assert(attrs.front.name == "name");
assert(attrs.front.value == "s");
assert(decodeXML(attrs.front.value) == "s");
}
}
}
version(dxmlTests) unittest
{
import core.exception : AssertError;
import std.algorithm.comparison : equal;
import std.exception : enforce;
import std.utf : byUTF;
import dxml.internal : testRangeFuncs;
static void test(alias func)(string text, string expected, size_t line = __LINE__)
{
auto range = func(text);
enforce!AssertError(range.save.decodeXML() == expected, "unittest failed 1", __FILE__, line);
alias C = ElementType!(typeof(range.save.asDecodedXML()));
enforce!AssertError(equal(range.save.asDecodedXML(), expected.byUTF!C), "unittest failed 2", __FILE__, line);
}
static foreach(func; testRangeFuncs)
{{
test!func("hello world & > < ' " \r\r\r\r\r foo", `hello world & > < ' " foo`);
test!func("&", "&");
test!func("�", "�");
test!func("&", "&");
test!func("&&&&", "&&&&");
test!func("&&&&", "&&&&");
test!func("&#", "&#");
test!func("&#;", "&#;");
test!func("�", "�");
test!func("�", "�");
test!func("0", "0");
test!func("�amp;", "�amp;");
test!func("&#amp;", "&#amp;");
test!func("&#x", "&#x");
test!func("&#x;", "&#x;");
test!func("�", "�");
test!func("	", "\t");
test!func(" ", " ");
test!func("ディラン", "ディラン");
}}
}
version(dxmlTests) @safe pure unittest
{
import std.algorithm.comparison : equal;
import dxml.internal : testRangeFuncs;
static foreach(func; testRangeFuncs)
{{
assert(decodeXML(func("foo")) == "foo");
assert(equal(asDecodedXML(func("foo")), "foo"));
}}
}
/++
$(H2 $(RED $(I Deprecated)))
normalize has been renamed to $(LREF decodeXML), and asNormalized has been
renamed to $(LREF asDecodedXML). It was pointed out that there's a fairly
high chance that $(PHOBOS_REF _normalize, std, uni) would be used in
conjunction with dxml, making conflicts annoyingly likely. Also, there was
no good opposite for normalize for the functions that became
$(LREF encodeAttr) and $(LREF encodeText). $(D denormalizeAttr) and
$(D denormalizeText) would arguably have been a bit ugly.
These aliases have been added to avoid code breakage when upgrading from
$(D dxml 0.2.*). They will be removed in $(D dxml 0.4.0).
+/
deprecated("normalize has been renamed to decodeXML. This alias will be removed in dxml 0.4.0.")
alias normalize = decodeXML;
/// Ditto
deprecated("asNormalized has been renamed to asDecodedXML. This alias will be removed in dxml 0.4.0.")
alias asNormalized = asDecodedXML;
version(dxmlTests) deprecated unittest
{
import core.exception : AssertError;
import std.algorithm.comparison : equal;
import std.exception : enforce;
import std.utf : byUTF;
import dxml.internal : testRangeFuncs;
// FIXME deprecated arguably shouldn't be required here since it's used on
// the unittest block. The bug should be reduced and reported.
deprecated static void test(alias func)(string text, string expected, size_t line = __LINE__)
{
auto range = func(text);
enforce!AssertError(range.save.normalize() == expected, "unittest failed 1", __FILE__, line);
alias C = ElementType!(typeof(range.save.asNormalized()));
enforce!AssertError(equal(range.save.asNormalized(), expected.byUTF!C), "unittest failed 2", __FILE__, line);
}
static foreach(func; testRangeFuncs)
{{
test!func("hello world & > < ' " \r\r\r\r\r foo", `hello world & > < ' " foo`);
test!func("&", "&");
test!func("�", "�");
test!func("&", "&");
test!func("&&&&", "&&&&");
test!func("&&&&", "&&&&");
test!func("&#", "&#");
test!func("&#;", "&#;");
test!func("�", "�");
test!func("�", "�");
test!func("0", "0");
test!func("�amp;", "�amp;");
test!func("&#amp;", "&#amp;");
test!func("&#x", "&#x");
test!func("&#x;", "&#x;");
test!func("�", "�");
test!func("	", "\t");
test!func(" ", " ");
test!func("ディラン", "ディラン");
}}
}
/++
This parses one of the five, predefined entity references mention in the XML
spec from the front of a range of characters.
If the given range starts with one of the five, predefined entity
references, then it is removed from the range, and the corresponding
character is returned.
If the range does not start with one of those references, then the return
value is null, and the range is unchanged.
$(TABLE
$(TR $(TH Std Entity Ref)$(TH Converts To))
$(TR $(TD $(D_CODE_STRING $(AMP)amp;))$(TD $(D_CODE_STRING &)))
$(TR $(TD $(D_CODE_STRING $(AMP)gt;))$(TD $(D_CODE_STRING >)))
$(TR $(TD $(D_CODE_STRING $(AMP)lt;))$(TD $(D_CODE_STRING $(LT))))
$(TR $(TD $(D_CODE_STRING $(AMP)apos;))$(TD $(D_CODE_STRING ')))
$(TR $(TD $(D_CODE_STRING $(AMP)quot;))$(TD $(D_CODE_STRING ")))
)
Any other entity references would require processing a DTD section in order
to be handled and are untouched by parseStdEntityRef as are any other types
of references.
Params:
range = A range of characters.
Returns: The character represented by the predefined entity reference that
was parsed from the front of the given range or null if the range
did not start with one of the five predefined entity references.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#dt-chardata)$(BR)
$(LREF parseCharRef)$(BR)
$(LREF decodeXML)$(BR)
$(LREF asDecodedXML)
+/
Nullable!dchar parseStdEntityRef(R)(ref R range)
if(isForwardRange!R && isSomeChar!(ElementType!R))
{
import std.algorithm.searching : startsWith;
import std.typecons : nullable, tuple;
import std.utf : byCodeUnit;
auto orig = range.save;
static if(isNarrowString!R)
auto cuRange = range.byCodeUnit();
else
alias cuRange = range;
if(!cuRange.save.startsWith('&'))
return typeof(return).init;
cuRange.popFront();
if(cuRange.empty)
goto invalid;
static foreach(t; [tuple("amp;", '&'), tuple("gt;", '>'), tuple("lt;", '<'),
tuple("apos;", '\''), tuple("quot;", '"')])
{
if(cuRange.save.startsWith(t[0]))
{
cuRange.popFrontN(t[0].length);
static if(isNarrowString!R)
range = cuRange.source;
return nullable(cast(dchar)t[1]);
}
}
invalid: range = orig;
return typeof(return).init;
}
///
version(dxmlTests) unittest
{
{
auto range = "&foo";
assert(range.parseStdEntityRef() == '&');
assert(range == "foo");
}
{
auto range = ">bar";
assert(range.parseStdEntityRef() == '>');
assert(range == "bar");
}
{
auto range = "<baz";
assert(range.parseStdEntityRef() == '<');
assert(range == "baz");
}
{
auto range = "'dlang";
assert(range.parseStdEntityRef() == '\'');
assert(range == "dlang");
}
{
auto range = ""rocks";
assert(range.parseStdEntityRef() == '"');
assert(range == "rocks");
}
{
auto range = " &foo";
assert(range.parseStdEntityRef().isNull);
assert(range == " &foo");
}
{
auto range = "&Amp;hello";
assert(range.parseStdEntityRef().isNull);
assert(range == "&Amp;hello");
}
{
auto range = " foo";
assert(range.parseStdEntityRef().isNull);
assert(range == " foo");
}
{
auto range = "hello world";
assert(range.parseStdEntityRef().isNull);
assert(range == "hello world");
}
}
version(dxmlTests) unittest
{
import std.algorithm.comparison : equal;
import dxml.internal : testRangeFuncs;
static foreach(func; testRangeFuncs)
{
for(auto range = func(";Amp;amp;&#amp;©& amp;"); !range.empty; range.popFront())
{
auto temp = range.save;
assert(temp.parseStdEntityRef().isNull);
assert(equal(range.save, temp.save));
}
{
auto range = func("&");
assert(range.parseStdEntityRef().isNull);
assert(equal(range.save, "&"));
}
{
auto range = func(" &><'"");
assert(range.parseStdEntityRef().isNull);
assert(equal(range.save, " &><'""));
range.popFront();
assert(range.parseStdEntityRef() == '&');
assert(equal(range.save, "><'""));
assert(range.parseStdEntityRef() == '>');
assert(equal(range.save, "<'""));
assert(range.parseStdEntityRef() == '<');
assert(equal(range.save, "'""));
assert(range.parseStdEntityRef() == '\'');
assert(equal(range.save, """));
assert(range.parseStdEntityRef() == '"');
assert(range.empty);
}
}
}
version(dxmlTests) @safe pure unittest
{
import dxml.internal : testRangeFuncs;
static foreach(func; testRangeFuncs)
{{
auto range = func("foo");
assert(range.parseStdEntityRef().isNull);
}}
}
/++
If the given range starts with a valid, XML, character reference, it is
removed from the range, and the corresponding character is returned.
If the range does not start with a valid, XML, character reference, then
the return value is null, and the range is unchanged.
Params:
range = A range of characters.
Returns: The character represented by the character reference that was
parsed from the front of the given range or null if the range did
not start with a valid, XML, character reference.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#NT-CharRef)$(BR)
$(LREF parseStdEntityRef)$(BR)
$(LREF decodeXML)$(BR)
$(LREF asDecodedXML)$(BR)
$(LREF encodeCharRef)
+/
Nullable!dchar parseCharRef(R)(ref R range)
if(isForwardRange!R && isSomeChar!(ElementType!R))
{
import std.algorithm.searching : startsWith;
import std.conv : ConvException, parse, to;
import std.range : popFrontN;
import std.typecons : nullable;
import std.utf : byCodeUnit;
import dxml.internal : isXMLChar;
auto orig = range.save;
static if(isNarrowString!R)
auto cuRange = range.byCodeUnit();
else
alias cuRange = range;
if(!cuRange.save.startsWith("&#"))
return typeof(return).init;
cuRange.popFrontN(2);
if(cuRange.empty)
goto invalid;
{
bool hex = false;
if(cuRange.front == 'x')
{
cuRange.popFront();
hex = true;
// https://issues.dlang.org/show_bug.cgi?id=18248
import std.ascii : isHexDigit;
if(cuRange.empty || !isHexDigit(cuRange.front))
goto invalid;
}
try
{
immutable c = to!dchar(cuRange.parse!uint(hex ? 16 : 10));
if(!cuRange.startsWith(';') || (c != '\n' && !isXMLChar(c)))
goto invalid;
cuRange.popFront();
static if(isNarrowString!R)
range = cuRange.source;
return nullable(cast()c);
}
catch(ConvException)
{}
}
invalid: range = orig;
return typeof(return).init;
}
///
version(dxmlTests) unittest
{
{
auto range = "0 hello world";
assert(parseCharRef(range) == '0');
assert(range == " hello world");
}
{
auto range = "0 hello world";
assert(parseCharRef(range) == '0');
assert(range == " hello world");
}
{
auto range = "ディラン";
assert(parseCharRef(range) == 'デ');
assert(range == "ィラン");
assert(parseCharRef(range) == 'ィ');
assert(range == "ラン");
assert(parseCharRef(range) == 'ラ');
assert(range == "ン");
assert(parseCharRef(range) == 'ン');
assert(range.empty);
}
{
auto range = "&#x;foo";
assert(parseCharRef(range).isNull);
assert(range == "&#x;foo");
}
{
auto range = "foobar";
assert(parseCharRef(range).isNull);
assert(range == "foobar");
}
{
auto range = " &x48;";
assert(parseCharRef(range).isNull);
assert(range == " &x48;");
}
}
version(dxmlTests) unittest
{
import std.algorithm.comparison : equal;
import dxml.internal : testRangeFuncs;
static foreach(func; testRangeFuncs)
{
for(auto range = func(";;&#;&#G;�&#F;"); !range.empty; range.popFront())
{
auto temp = range.save;
assert(temp.parseCharRef().isNull);
assert(equal(range.save, temp.save));
}
{
auto range = func("A");
assert(range.parseCharRef().isNull);
assert(equal(range.save, "A"));
}
{
auto range = func(" ABC 京都市");
assert(range.parseCharRef().isNull);
assert(equal(range.save, " ABC 京都市"));
range.popFront();
assert(range.parseCharRef() == 'A');
assert(equal(range.save, "BC 京都市"));
assert(range.parseCharRef() == 'B');
assert(equal(range.save, "C 京都市"));
assert(range.parseCharRef() == 'C');
assert(equal(range.save, " 京都市"));
assert(range.parseCharRef().isNull);
assert(equal(range.save, " 京都市"));
range.popFront();
assert(range.parseCharRef() == '京');
assert(equal(range.save, "都市"));
assert(range.parseCharRef() == '都');
assert(equal(range.save, "市"));
assert(range.parseCharRef() == '市');
assert(range.empty);
}
}
}
version(dxmlTests) @safe pure unittest
{
import dxml.internal : testRangeFuncs;
static foreach(func; testRangeFuncs)
{{
auto range = func("foo");
assert(range.parseCharRef().isNull);
}}
}
/++
Strips the indent from a character range (most likely from
$(REF_ALTTEXT Entity.text, EntityRange.Entity.text, dxml, parser)).
The idea is that if the XML is formatted to be human-readable, and it's
multiple lines long, the lines are likely to be indented, but the
application probably doesn't want that extra whitespace. So, stripIndent
and withoutIndent attempt to intelligently strip off the leading
whitespace.
For these functions, whitespace is considered to be some combination of
$(D_CODE_STRING ' '), $(D_CODE_STRING '\t'), and $(D_CODE_STRING '\r')
($(D_CODE_STRING '\n') is used to delineate lines, so it's not considered
whitespace).
Whitespace characters are stripped from the start of the first line, and
then those same number of whitespace characters are stripped from the
beginning of each subsequent line (or up to the first non-whitespace
character if the line starts with fewer whitespace characters).
If the first line has no leading whitespace, then the leading whitespace on
the second line is treated as the indent. This is done to handle case where
there is text immediately after a start tag and then subsequent lines are
indented rather than the text starting on the line after the start tag.
If neither of the first two lines has any leading whitespace, then no
whitespace is stripped.
So, if the text is well-formatted, then the indent should be cleanly
removed, and if it's unformatted or badly formatted, then no characters
other than leading whitespace will be removed, and in principle, no real
data will have been lost - though of course, it's up to the programmer to
decide whether it's better for the application to try to cleanly strip the
indent or to leave the text as-is.
The difference between stripIndent and withoutIndent is that stripIndent
returns a $(K_STRING), whereas withoutIndent returns a lazy range
of code units. In the case where a $(K_STRING) is passed to
stripIndent, it will simply return the original string if there is no
indent (whereas in other cases, stripIndent and withoutIndent are forced to
return new ranges).
Params:
range = A range of characters.
Returns: The text with the indent stripped from each line. stripIndent
returns a $(K_STRING), whereas withoutIndent returns a lazy range
of code units (so it could be a range of $(K_CHAR) or $(K_WCHAR)
and not just $(K_DCHAR); which it is depends on the code units of
the range being passed in).
See_Also: $(REF EntityRange.Entity.text, dxml, parser)
+/
string stripIndent(R)(R range)
if(isForwardRange!R && isSomeChar!(ElementType!R))
{
static if(isDynamicArray!R && is(Unqual!(ElementEncodingType!R) == char))
{
static bool notHWhite(char c)
{
switch(c)
{
case ' ':
case '\t':
case '\r': return false;
default : return true;
}
}
import std.algorithm.searching : find;
import std.utf : byCodeUnit;
if(range.empty)
return range;
auto orig = range.save;
auto text = range.byCodeUnit();
string firstLine;
if(notHWhite(text.front))
{
text = text.find('\n');
if(text.empty)
return orig;
text.popFront();
firstLine = orig[0 .. orig.length - text.length];
}
immutable beforeIndent = text.length;
text = text.find!notHWhite();
if(text.empty)
return text.source;
immutable indent = beforeIndent - text.length;
if(indent == 0)
return orig;
import std.array : appender;
auto retval = appender!string();
retval.reserve(orig.length / 3);
// > 1 because we don't want a newline by itself.
if(firstLine.length > 1)
put(retval, firstLine);
outer: while(true)
{
auto start = text.save;
text = text.find('\n');
if(text.empty)
{
if(!start.empty)
put(retval, start);
return retval.data;
}
text.popFront();
auto line = start[0 .. $ - text.length];
foreach(_; 0 .. indent)
{
if(text.empty)
goto isEmpty;
if(notHWhite(text.front))
goto notEmpty;
text.popFront();
}
if(text.empty)
{
isEmpty: put(retval, line[0 .. $ - 1]);
return retval.data;
}
notEmpty: put(retval, line);
}