-
-
Notifications
You must be signed in to change notification settings - Fork 707
/
Copy pathutf.d
4731 lines (4202 loc) · 147 KB
/
utf.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.
/++
Encode and decode UTF-8, UTF-16 and UTF-32 strings.
UTF character support is restricted to
$(D '\u0000' <= character <= '\U0010FFFF').
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Decode) $(TD
$(LREF decode)
$(LREF decodeFront)
))
$(TR $(TD Lazy decode) $(TD
$(LREF byCodeUnit)
$(LREF byChar)
$(LREF byWchar)
$(LREF byDchar)
$(LREF byUTF)
))
$(TR $(TD Encode) $(TD
$(LREF encode)
$(LREF toUTF8)
$(LREF toUTF16)
$(LREF toUTF32)
$(LREF toUTFz)
$(LREF toUTF16z)
))
$(TR $(TD Length) $(TD
$(LREF codeLength)
$(LREF count)
$(LREF stride)
$(LREF strideBack)
))
$(TR $(TD Index) $(TD
$(LREF toUCSindex)
$(LREF toUTFindex)
))
$(TR $(TD Validation) $(TD
$(LREF isValidDchar)
$(LREF isValidCodepoint)
$(LREF validate)
))
$(TR $(TD Miscellaneous) $(TD
$(LREF replacementDchar)
$(LREF UseReplacementDchar)
$(LREF UTFException)
))
))
See_Also:
$(LINK2 http://en.wikipedia.org/wiki/Unicode, Wikipedia)<br>
$(LINK http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8)<br>
$(LINK https://web.archive.org/web/20100113043530/https://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335)
Copyright: Copyright The D Language Foundation 2000 - 2012.
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP digitalmars.com, Walter Bright) and
$(HTTP jmdavisprog.com, Jonathan M Davis)
Source: $(PHOBOSSRC std/utf.d)
+/
module std.utf;
import std.exception : basicExceptionCtors;
import core.exception : UnicodeException;
import std.meta : AliasSeq;
import std.range;
import std.traits : isAutodecodableString, isConvertibleToString,
isSomeChar, isSomeString, isStaticArray, Unqual;
import std.typecons : Flag, Yes, No;
/++
Exception thrown on errors in std.utf functions.
+/
class UTFException : UnicodeException
{
import core.internal.string : unsignedToTempString, UnsignedStringBuf;
uint[4] sequence;
size_t len;
@safe pure nothrow @nogc
UTFException setSequence(scope uint[] data...) return
{
assert(data.length <= 4);
len = data.length < 4 ? data.length : 4;
sequence[0 .. len] = data[0 .. len];
return this;
}
// FIXME: Use std.exception.basicExceptionCtors here once
// https://issues.dlang.org/show_bug.cgi?id=11500 is fixed
/**
Standard exception constructors.
*/
this(string msg, string file = __FILE__, size_t line = __LINE__,
Throwable next = null) @nogc @safe pure nothrow
{
super(msg, 0, file, line, next);
}
/// ditto
this(string msg, size_t index, string file = __FILE__,
size_t line = __LINE__, Throwable next = null) @safe pure nothrow
{
UnsignedStringBuf buf = void;
msg ~= " (at index " ~ unsignedToTempString(index, buf) ~ ")";
super(msg, index, file, line, next);
}
/**
Returns:
A `string` detailing the invalid UTF sequence.
*/
override string toString() const
{
if (len == 0)
{
/* Exception.toString() is not marked as const, although
* it is const-compatible.
*/
//return super.toString();
auto e = () @trusted { return cast(Exception) super; } ();
return e.toString();
}
string result = "Invalid UTF sequence:";
foreach (i; sequence[0 .. len])
{
UnsignedStringBuf buf = void;
result ~= ' ';
auto h = unsignedToTempString!16(i, buf);
if (h.length == 1)
result ~= '0';
result ~= h;
result ~= 'x';
}
if (super.msg.length > 0)
{
result ~= " - ";
result ~= super.msg;
}
return result;
}
}
///
@safe unittest
{
import std.exception : assertThrown;
char[4] buf;
assertThrown!UTFException(encode(buf, cast(dchar) 0xD800));
assertThrown!UTFException(encode(buf, cast(dchar) 0xDBFF));
assertThrown!UTFException(encode(buf, cast(dchar) 0xDC00));
assertThrown!UTFException(encode(buf, cast(dchar) 0xDFFF));
assertThrown!UTFException(encode(buf, cast(dchar) 0x110000));
}
/*
Provide array of invalidly encoded UTF strings. Useful for testing.
Params:
Char = char, wchar, or dchar
Returns:
an array of invalidly encoded UTF strings
*/
package auto invalidUTFstrings(Char)() @safe pure @nogc nothrow
if (isSomeChar!Char)
{
static if (is(Char == char))
{
enum x = 0xDC00; // invalid surrogate value
enum y = 0x110000; // out of range
static immutable string[8] result =
[
"\x80", // not a start byte
"\xC0", // truncated
"\xC0\xC0", // invalid continuation
"\xF0\x82\x82\xAC", // overlong
[
0xE0 | (x >> 12),
0x80 | ((x >> 6) & 0x3F),
0x80 | (x & 0x3F)
],
[
cast(char)(0xF0 | (y >> 18)),
cast(char)(0x80 | ((y >> 12) & 0x3F)),
cast(char)(0x80 | ((y >> 6) & 0x3F)),
cast(char)(0x80 | (y & 0x3F))
],
[
cast(char)(0xF8 | 3), // 5 byte encoding
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
],
[
cast(char)(0xFC | 3), // 6 byte encoding
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
cast(char)(0x80 | 3),
],
];
return result[];
}
else static if (is(Char == wchar))
{
static immutable wstring[5] result =
[
[
cast(wchar) 0xDC00,
],
[
cast(wchar) 0xDFFF,
],
[
cast(wchar) 0xDBFF,
cast(wchar) 0xDBFF,
],
[
cast(wchar) 0xDBFF,
cast(wchar) 0xE000,
],
[
cast(wchar) 0xD800,
],
];
return result[];
}
else static if (is(Char == dchar))
{
static immutable dstring[3] result =
[
[ cast(dchar) 0x110000 ],
[ cast(dchar) 0x00D800 ],
[ cast(dchar) 0x00DFFF ],
];
return result;
}
else
static assert(0);
}
/++
Check whether the given Unicode code point is valid.
Params:
c = code point to check
Returns:
`true` if and only if `c` is a valid Unicode code point
Note:
`'\uFFFE'` and `'\uFFFF'` are considered valid by `isValidDchar`,
as they are permitted for internal use by an application, but they are
not allowed for interchange by the Unicode standard.
+/
bool isValidDchar(dchar c) pure nothrow @safe @nogc
{
return c < 0xD800 || (c > 0xDFFF && c <= 0x10FFFF);
}
///
@safe @nogc pure nothrow unittest
{
assert( isValidDchar(cast(dchar) 0x41));
assert( isValidDchar(cast(dchar) 0x00));
assert(!isValidDchar(cast(dchar) 0xD800));
assert(!isValidDchar(cast(dchar) 0x11FFFF));
}
pure nothrow @safe @nogc unittest
{
import std.exception;
assertCTFEable!(
{
assert( isValidDchar(cast(dchar)'a') == true);
assert( isValidDchar(cast(dchar) 0x1FFFFF) == false);
assert(!isValidDchar(cast(dchar) 0x00D800));
assert(!isValidDchar(cast(dchar) 0x00DBFF));
assert(!isValidDchar(cast(dchar) 0x00DC00));
assert(!isValidDchar(cast(dchar) 0x00DFFF));
assert( isValidDchar(cast(dchar) 0x00FFFE));
assert( isValidDchar(cast(dchar) 0x00FFFF));
assert( isValidDchar(cast(dchar) 0x01FFFF));
assert( isValidDchar(cast(dchar) 0x10FFFF));
assert(!isValidDchar(cast(dchar) 0x110000));
});
}
/**
Checks if a single character forms a valid code point.
When standing alone, some characters are invalid code points. For
example the `wchar` `0xD800` is a so called high surrogate, which can
only be interpreted together with a low surrogate following it. As a
standalone character it is considered invalid.
See $(LINK2 http://www.unicode.org/versions/Unicode13.0.0/,
Unicode Standard, D90, D91 and D92) for more details.
Params:
c = character to test
Char = character type of `c`
Returns:
`true`, if `c` forms a valid code point.
*/
bool isValidCodepoint(Char)(Char c)
if (isSomeChar!Char)
{
alias UChar = typeof(cast() c);
static if (is(UChar == char))
{
return c <= 0x7F;
}
else static if (is(UChar == wchar))
{
return c <= 0xD7FF || c >= 0xE000;
}
else static if (is(UChar == dchar))
{
return isValidDchar(c);
}
else
static assert(false, "unknown character type: `" ~ Char.stringof ~ "`");
}
///
@safe pure nothrow unittest
{
assert( isValidCodepoint(cast(char) 0x40));
assert(!isValidCodepoint(cast(char) 0x80));
assert( isValidCodepoint(cast(wchar) 0x1234));
assert(!isValidCodepoint(cast(wchar) 0xD800));
assert( isValidCodepoint(cast(dchar) 0x0010FFFF));
assert(!isValidCodepoint(cast(dchar) 0x12345678));
}
/++
Calculate the length of the UTF sequence starting at `index`
in `str`.
Params:
str = $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of UTF code units. Must be random access if `index` is passed
index = starting index of UTF sequence (default: `0`)
Returns:
The number of code units in the UTF sequence. For UTF-8, this is a
value between 1 and 4 (as per $(HTTP tools.ietf.org/html/rfc3629#section-3, RFC 3629$(COMMA) section 3)).
For UTF-16, it is either 1 or 2. For UTF-32, it is always 1.
Throws:
May throw a `UTFException` if `str[index]` is not the start of a
valid UTF sequence.
Note:
`stride` will only analyze the first `str[index]` element. It
will not fully verify the validity of the UTF sequence, nor even verify
the presence of the sequence: it will not actually guarantee that
$(D index + stride(str, index) <= str.length).
+/
uint stride(S)(auto ref S str, size_t index)
if (is(S : const char[]) ||
(isRandomAccessRange!S && is(immutable ElementType!S == immutable char)))
{
static if (is(typeof(str.length) : ulong))
assert(index < str.length, "Past the end of the UTF-8 sequence");
immutable c = str[index];
if (c < 0x80)
return 1;
else
return strideImpl(c, index);
}
/// Ditto
uint stride(S)(auto ref S str)
if (is(S : const char[]) ||
(isInputRange!S && is(immutable ElementType!S == immutable char)))
{
static if (is(S : const char[]))
immutable c = str[0];
else
immutable c = str.front;
if (c < 0x80)
return 1;
else
return strideImpl(c, 0);
}
@system unittest
{
import core.exception : AssertError;
import std.conv : to;
import std.exception;
import std.string : format;
import std.traits : FunctionAttribute, functionAttributes, isSafe;
static void test(string s, dchar c, size_t i = 0, size_t line = __LINE__)
{
enforce(stride(s, i) == codeLength!char(c),
new AssertError(format("Unit test failure string: %s", s), __FILE__, line));
enforce(stride(RandomCU!char(s), i) == codeLength!char(c),
new AssertError(format("Unit test failure range: %s", s), __FILE__, line));
auto refRandom = new RefRandomCU!char(s);
immutable randLen = refRandom.length;
enforce(stride(refRandom, i) == codeLength!char(c),
new AssertError(format("Unit test failure rand ref range: %s", s), __FILE__, line));
enforce(refRandom.length == randLen,
new AssertError(format("Unit test failure rand ref range length: %s", s), __FILE__, line));
if (i == 0)
{
enforce(stride(s) == codeLength!char(c),
new AssertError(format("Unit test failure string 0: %s", s), __FILE__, line));
enforce(stride(InputCU!char(s)) == codeLength!char(c),
new AssertError(format("Unit test failure range 0: %s", s), __FILE__, line));
auto refBidir = new RefBidirCU!char(s);
immutable bidirLen = refBidir.length;
enforce(stride(refBidir) == codeLength!char(c),
new AssertError(format("Unit test failure bidir ref range code length: %s", s), __FILE__, line));
enforce(refBidir.length == bidirLen,
new AssertError(format("Unit test failure bidir ref range length: %s", s), __FILE__, line));
}
}
assertCTFEable!(
{
test("a", 'a');
test(" ", ' ');
test("\u2029", '\u2029'); //paraSep
test("\u0100", '\u0100');
test("\u0430", '\u0430');
test("\U00010143", '\U00010143');
test("abcdefcdef", 'a');
test("hello\U00010143\u0100\U00010143", 'h', 0);
test("hello\U00010143\u0100\U00010143", 'e', 1);
test("hello\U00010143\u0100\U00010143", 'l', 2);
test("hello\U00010143\u0100\U00010143", 'l', 3);
test("hello\U00010143\u0100\U00010143", 'o', 4);
test("hello\U00010143\u0100\U00010143", '\U00010143', 5);
test("hello\U00010143\u0100\U00010143", '\u0100', 9);
test("hello\U00010143\u0100\U00010143", '\U00010143', 11);
foreach (S; AliasSeq!(char[], const char[], string))
{
enum str = to!S("hello world");
static assert(isSafe!({ stride(str, 0); }));
static assert(isSafe!({ stride(str); }));
static assert((functionAttributes!({ stride(str, 0); }) & FunctionAttribute.pure_) != 0);
static assert((functionAttributes!({ stride(str); }) & FunctionAttribute.pure_) != 0);
}
});
}
@safe unittest // invalid start bytes
{
import std.exception : assertThrown;
immutable char[] invalidStartBytes = [
0b1111_1000, // indicating a sequence length of 5
0b1111_1100, // 6
0b1111_1110, // 7
0b1111_1111, // 8
0b1000_0000, // continuation byte
];
foreach (c; invalidStartBytes)
assertThrown!UTFException(stride([c]));
}
/// Ditto
uint stride(S)(auto ref S str, size_t index)
if (is(S : const wchar[]) ||
(isRandomAccessRange!S && is(immutable ElementType!S == immutable wchar)))
{
static if (is(typeof(str.length) : ulong))
assert(index < str.length, "Past the end of the UTF-16 sequence");
immutable uint u = str[index];
return 1 + (u >= 0xD800 && u <= 0xDBFF);
}
/// Ditto
uint stride(S)(auto ref S str) @safe pure
if (is(S : const wchar[]))
{
return stride(str, 0);
}
/// Ditto
uint stride(S)(auto ref S str)
if (isInputRange!S && is(immutable ElementType!S == immutable wchar) &&
!is(S : const wchar[]))
{
assert(!str.empty, "UTF-16 sequence is empty");
immutable uint u = str.front;
return 1 + (u >= 0xD800 && u <= 0xDBFF);
}
@system unittest
{
import core.exception : AssertError;
import std.conv : to;
import std.exception;
import std.string : format;
import std.traits : FunctionAttribute, functionAttributes, isSafe;
static void test(wstring s, dchar c, size_t i = 0, size_t line = __LINE__)
{
enforce(stride(s, i) == codeLength!wchar(c),
new AssertError(format("Unit test failure string: %s", s), __FILE__, line));
enforce(stride(RandomCU!wchar(s), i) == codeLength!wchar(c),
new AssertError(format("Unit test failure range: %s", s), __FILE__, line));
auto refRandom = new RefRandomCU!wchar(s);
immutable randLen = refRandom.length;
enforce(stride(refRandom, i) == codeLength!wchar(c),
new AssertError(format("Unit test failure rand ref range: %s", s), __FILE__, line));
enforce(refRandom.length == randLen,
new AssertError(format("Unit test failure rand ref range length: %s", s), __FILE__, line));
if (i == 0)
{
enforce(stride(s) == codeLength!wchar(c),
new AssertError(format("Unit test failure string 0: %s", s), __FILE__, line));
enforce(stride(InputCU!wchar(s)) == codeLength!wchar(c),
new AssertError(format("Unit test failure range 0: %s", s), __FILE__, line));
auto refBidir = new RefBidirCU!wchar(s);
immutable bidirLen = refBidir.length;
enforce(stride(refBidir) == codeLength!wchar(c),
new AssertError(format("Unit test failure bidir ref range code length: %s", s), __FILE__, line));
enforce(refBidir.length == bidirLen,
new AssertError(format("Unit test failure bidir ref range length: %s", s), __FILE__, line));
}
}
assertCTFEable!(
{
test("a", 'a');
test(" ", ' ');
test("\u2029", '\u2029'); //paraSep
test("\u0100", '\u0100');
test("\u0430", '\u0430');
test("\U00010143", '\U00010143');
test("abcdefcdef", 'a');
test("hello\U00010143\u0100\U00010143", 'h', 0);
test("hello\U00010143\u0100\U00010143", 'e', 1);
test("hello\U00010143\u0100\U00010143", 'l', 2);
test("hello\U00010143\u0100\U00010143", 'l', 3);
test("hello\U00010143\u0100\U00010143", 'o', 4);
test("hello\U00010143\u0100\U00010143", '\U00010143', 5);
test("hello\U00010143\u0100\U00010143", '\u0100', 7);
test("hello\U00010143\u0100\U00010143", '\U00010143', 8);
foreach (S; AliasSeq!(wchar[], const wchar[], wstring))
{
enum str = to!S("hello world");
static assert(isSafe!(() => stride(str, 0)));
static assert(isSafe!(() => stride(str) ));
static assert((functionAttributes!(() => stride(str, 0)) & FunctionAttribute.pure_) != 0);
static assert((functionAttributes!(() => stride(str) ) & FunctionAttribute.pure_) != 0);
}
});
}
/// Ditto
uint stride(S)(auto ref S str, size_t index = 0)
if (is(S : const dchar[]) ||
(isInputRange!S && is(immutable ElementEncodingType!S == immutable dchar)))
{
static if (is(typeof(str.length) : ulong))
assert(index < str.length, "Past the end of the UTF-32 sequence");
else
assert(!str.empty, "UTF-32 sequence is empty.");
return 1;
}
///
@safe unittest
{
assert("a".stride == 1);
assert("λ".stride == 2);
assert("aλ".stride == 1);
assert("aλ".stride(1) == 2);
assert("𐐷".stride == 4);
}
@system unittest
{
import core.exception : AssertError;
import std.conv : to;
import std.exception;
import std.string : format;
import std.traits : FunctionAttribute, functionAttributes, isSafe;
static void test(dstring s, dchar c, size_t i = 0, size_t line = __LINE__)
{
enforce(stride(s, i) == codeLength!dchar(c),
new AssertError(format("Unit test failure string: %s", s), __FILE__, line));
enforce(stride(RandomCU!dchar(s), i) == codeLength!dchar(c),
new AssertError(format("Unit test failure range: %s", s), __FILE__, line));
auto refRandom = new RefRandomCU!dchar(s);
immutable randLen = refRandom.length;
enforce(stride(refRandom, i) == codeLength!dchar(c),
new AssertError(format("Unit test failure rand ref range: %s", s), __FILE__, line));
enforce(refRandom.length == randLen,
new AssertError(format("Unit test failure rand ref range length: %s", s), __FILE__, line));
if (i == 0)
{
enforce(stride(s) == codeLength!dchar(c),
new AssertError(format("Unit test failure string 0: %s", s), __FILE__, line));
enforce(stride(InputCU!dchar(s)) == codeLength!dchar(c),
new AssertError(format("Unit test failure range 0: %s", s), __FILE__, line));
auto refBidir = new RefBidirCU!dchar(s);
immutable bidirLen = refBidir.length;
enforce(stride(refBidir) == codeLength!dchar(c),
new AssertError(format("Unit test failure bidir ref range code length: %s", s), __FILE__, line));
enforce(refBidir.length == bidirLen,
new AssertError(format("Unit test failure bidir ref range length: %s", s), __FILE__, line));
}
}
assertCTFEable!(
{
test("a", 'a');
test(" ", ' ');
test("\u2029", '\u2029'); //paraSep
test("\u0100", '\u0100');
test("\u0430", '\u0430');
test("\U00010143", '\U00010143');
test("abcdefcdef", 'a');
test("hello\U00010143\u0100\U00010143", 'h', 0);
test("hello\U00010143\u0100\U00010143", 'e', 1);
test("hello\U00010143\u0100\U00010143", 'l', 2);
test("hello\U00010143\u0100\U00010143", 'l', 3);
test("hello\U00010143\u0100\U00010143", 'o', 4);
test("hello\U00010143\u0100\U00010143", '\U00010143', 5);
test("hello\U00010143\u0100\U00010143", '\u0100', 6);
test("hello\U00010143\u0100\U00010143", '\U00010143', 7);
foreach (S; AliasSeq!(dchar[], const dchar[], dstring))
{
enum str = to!S("hello world");
static assert(isSafe!(() => stride(str, 0)));
static assert(isSafe!(() => stride(str) ));
static assert((functionAttributes!(() => stride(str, 0)) & FunctionAttribute.pure_) != 0);
static assert((functionAttributes!(() => stride(str) ) & FunctionAttribute.pure_) != 0);
}
});
}
private uint strideImpl(char c, size_t index) @trusted pure
in { assert(c & 0x80); }
do
{
import core.bitop : bsr;
immutable msbs = 7 - bsr((~uint(c)) & 0xFF);
if (c == 0xFF || msbs < 2 || msbs > 4)
throw new UTFException("Invalid UTF-8 sequence", index);
return msbs;
}
/++
Calculate the length of the UTF sequence ending one code unit before
`index` in `str`.
Params:
str = bidirectional range of UTF code units. Must be random access if
`index` is passed
index = index one past end of UTF sequence (default: `str.length`)
Returns:
The number of code units in the UTF sequence. For UTF-8, this is a
value between 1 and 4 (as per $(HTTP tools.ietf.org/html/rfc3629#section-3, RFC 3629$(COMMA) section 3)).
For UTF-16, it is either 1 or 2. For UTF-32, it is always 1.
Throws:
May throw a `UTFException` if `str[index]` is not one past the
end of a valid UTF sequence.
Note:
`strideBack` will only analyze the element at $(D str[index - 1])
element. It will not fully verify the validity of the UTF sequence, nor
even verify the presence of the sequence: it will not actually
guarantee that $(D strideBack(str, index) <= index).
+/
uint strideBack(S)(auto ref S str, size_t index)
if (is(S : const char[]) ||
(isRandomAccessRange!S && is(immutable ElementType!S == immutable char)))
{
static if (is(typeof(str.length) : ulong))
assert(index <= str.length, "Past the end of the UTF-8 sequence");
assert(index > 0, "Not the end of the UTF-8 sequence");
if ((str[index-1] & 0b1100_0000) != 0b1000_0000)
return 1;
if (index >= 4) //single verification for most common case
{
static foreach (i; 2 .. 5)
{
if ((str[index-i] & 0b1100_0000) != 0b1000_0000)
return i;
}
}
else
{
static foreach (i; 2 .. 4)
{
if (index >= i && (str[index-i] & 0b1100_0000) != 0b1000_0000)
return i;
}
}
throw new UTFException("Not the end of the UTF sequence", index);
}
/// Ditto
uint strideBack(S)(auto ref S str)
if (is(S : const char[]) ||
(isRandomAccessRange!S && hasLength!S && is(immutable ElementType!S == immutable char)))
{
return strideBack(str, str.length);
}
/// Ditto
uint strideBack(S)(auto ref S str)
if (isBidirectionalRange!S && is(immutable ElementType!S == immutable char) && !isRandomAccessRange!S)
{
assert(!str.empty, "Past the end of the UTF-8 sequence");
auto temp = str.save;
foreach (i; AliasSeq!(1, 2, 3, 4))
{
if ((temp.back & 0b1100_0000) != 0b1000_0000)
return i;
temp.popBack();
if (temp.empty)
break;
}
throw new UTFException("The last code unit is not the end of the UTF-8 sequence");
}
@system unittest
{
import core.exception : AssertError;
import std.conv : to;
import std.exception;
import std.string : format;
import std.traits : FunctionAttribute, functionAttributes, isSafe;
static void test(string s, dchar c, size_t i = size_t.max, size_t line = __LINE__)
{
enforce(strideBack(s, i == size_t.max ? s.length : i) == codeLength!char(c),
new AssertError(format("Unit test failure string: %s", s), __FILE__, line));
enforce(strideBack(RandomCU!char(s), i == size_t.max ? s.length : i) == codeLength!char(c),
new AssertError(format("Unit test failure range: %s", s), __FILE__, line));
auto refRandom = new RefRandomCU!char(s);
immutable randLen = refRandom.length;
enforce(strideBack(refRandom, i == size_t.max ? s.length : i) == codeLength!char(c),
new AssertError(format("Unit test failure rand ref range: %s", s), __FILE__, line));
enforce(refRandom.length == randLen,
new AssertError(format("Unit test failure rand ref range length: %s", s), __FILE__, line));
if (i == size_t.max)
{
enforce(strideBack(s) == codeLength!char(c),
new AssertError(format("Unit test failure string code length: %s", s), __FILE__, line));
enforce(strideBack(BidirCU!char(s)) == codeLength!char(c),
new AssertError(format("Unit test failure range code length: %s", s), __FILE__, line));
auto refBidir = new RefBidirCU!char(s);
immutable bidirLen = refBidir.length;
enforce(strideBack(refBidir) == codeLength!char(c),
new AssertError(format("Unit test failure bidir ref range code length: %s", s), __FILE__, line));
enforce(refBidir.length == bidirLen,
new AssertError(format("Unit test failure bidir ref range length: %s", s), __FILE__, line));
}
}
assertCTFEable!(
{
test("a", 'a');
test(" ", ' ');
test("\u2029", '\u2029'); //paraSep
test("\u0100", '\u0100');
test("\u0430", '\u0430');
test("\U00010143", '\U00010143');
test("abcdefcdef", 'f');
test("\U00010143\u0100\U00010143hello", 'o', 15);
test("\U00010143\u0100\U00010143hello", 'l', 14);
test("\U00010143\u0100\U00010143hello", 'l', 13);
test("\U00010143\u0100\U00010143hello", 'e', 12);
test("\U00010143\u0100\U00010143hello", 'h', 11);
test("\U00010143\u0100\U00010143hello", '\U00010143', 10);
test("\U00010143\u0100\U00010143hello", '\u0100', 6);
test("\U00010143\u0100\U00010143hello", '\U00010143', 4);
foreach (S; AliasSeq!(char[], const char[], string))
{
enum str = to!S("hello world");
static assert(isSafe!({ strideBack(str, 0); }));
static assert(isSafe!({ strideBack(str); }));
static assert((functionAttributes!({ strideBack(str, 0); }) & FunctionAttribute.pure_) != 0);
static assert((functionAttributes!({ strideBack(str); }) & FunctionAttribute.pure_) != 0);
}
});
}
//UTF-16 is self synchronizing: The length of strideBack can be found from
//the value of a single wchar
/// Ditto
uint strideBack(S)(auto ref S str, size_t index)
if (is(S : const wchar[]) ||
(isRandomAccessRange!S && is(immutable ElementType!S == immutable wchar)))
{
static if (is(typeof(str.length) : ulong))
assert(index <= str.length, "Past the end of the UTF-16 sequence");
assert(index > 0, "Not the end of a UTF-16 sequence");
immutable c2 = str[index-1];
return 1 + (0xDC00 <= c2 && c2 < 0xE000);
}
/// Ditto
uint strideBack(S)(auto ref S str)
if (is(S : const wchar[]) ||
(isBidirectionalRange!S && is(immutable ElementType!S == immutable wchar)))
{
assert(!str.empty, "UTF-16 sequence is empty");
static if (is(S : const(wchar)[]))
immutable c2 = str[$ - 1];
else
immutable c2 = str.back;
return 1 + (0xDC00 <= c2 && c2 <= 0xE000);
}
@system unittest
{
import core.exception : AssertError;
import std.conv : to;
import std.exception;
import std.string : format;
import std.traits : FunctionAttribute, functionAttributes, isSafe;
static void test(wstring s, dchar c, size_t i = size_t.max, size_t line = __LINE__)
{
enforce(strideBack(s, i == size_t.max ? s.length : i) == codeLength!wchar(c),
new AssertError(format("Unit test failure string: %s", s), __FILE__, line));
enforce(strideBack(RandomCU!wchar(s), i == size_t.max ? s.length : i) == codeLength!wchar(c),
new AssertError(format("Unit test failure range: %s", s), __FILE__, line));
auto refRandom = new RefRandomCU!wchar(s);
immutable randLen = refRandom.length;
enforce(strideBack(refRandom, i == size_t.max ? s.length : i) == codeLength!wchar(c),
new AssertError(format("Unit test failure rand ref range: %s", s), __FILE__, line));
enforce(refRandom.length == randLen,
new AssertError(format("Unit test failure rand ref range length: %s", s), __FILE__, line));
if (i == size_t.max)
{
enforce(strideBack(s) == codeLength!wchar(c),
new AssertError(format("Unit test failure string code length: %s", s), __FILE__, line));
enforce(strideBack(BidirCU!wchar(s)) == codeLength!wchar(c),
new AssertError(format("Unit test failure range code length: %s", s), __FILE__, line));
auto refBidir = new RefBidirCU!wchar(s);
immutable bidirLen = refBidir.length;
enforce(strideBack(refBidir) == codeLength!wchar(c),
new AssertError(format("Unit test failure bidir ref range code length: %s", s), __FILE__, line));
enforce(refBidir.length == bidirLen,
new AssertError(format("Unit test failure bidir ref range length: %s", s), __FILE__, line));
}
}
assertCTFEable!(
{
test("a", 'a');
test(" ", ' ');
test("\u2029", '\u2029'); //paraSep
test("\u0100", '\u0100');
test("\u0430", '\u0430');
test("\U00010143", '\U00010143');
test("abcdefcdef", 'f');
test("\U00010143\u0100\U00010143hello", 'o', 10);
test("\U00010143\u0100\U00010143hello", 'l', 9);
test("\U00010143\u0100\U00010143hello", 'l', 8);
test("\U00010143\u0100\U00010143hello", 'e', 7);
test("\U00010143\u0100\U00010143hello", 'h', 6);
test("\U00010143\u0100\U00010143hello", '\U00010143', 5);
test("\U00010143\u0100\U00010143hello", '\u0100', 3);
test("\U00010143\u0100\U00010143hello", '\U00010143', 2);
foreach (S; AliasSeq!(wchar[], const wchar[], wstring))
{
enum str = to!S("hello world");
static assert(isSafe!(() => strideBack(str, 0)));
static assert(isSafe!(() => strideBack(str) ));
static assert((functionAttributes!(() => strideBack(str, 0)) & FunctionAttribute.pure_) != 0);
static assert((functionAttributes!(() => strideBack(str) ) & FunctionAttribute.pure_) != 0);
}
});
}
/// Ditto
uint strideBack(S)(auto ref S str, size_t index)
if (isRandomAccessRange!S && is(immutable ElementEncodingType!S == immutable dchar))
{
static if (is(typeof(str.length) : ulong))
assert(index <= str.length, "Past the end of the UTF-32 sequence");
assert(index > 0, "Not the end of the UTF-32 sequence");
return 1;
}
/// Ditto
uint strideBack(S)(auto ref S str)
if (isBidirectionalRange!S && is(immutable ElementEncodingType!S == immutable dchar))
{
assert(!str.empty, "Empty UTF-32 sequence");
return 1;
}
///
@safe unittest
{
assert("a".strideBack == 1);
assert("λ".strideBack == 2);
assert("aλ".strideBack == 2);
assert("aλ".strideBack(1) == 1);
assert("𐐷".strideBack == 4);
}
@system unittest
{
import core.exception : AssertError;
import std.conv : to;
import std.exception;
import std.string : format;
import std.traits : FunctionAttribute, functionAttributes, isSafe;
static void test(dstring s, dchar c, size_t i = size_t.max, size_t line = __LINE__)
{
enforce(strideBack(s, i == size_t.max ? s.length : i) == codeLength!dchar(c),
new AssertError(format("Unit test failure string: %s", s), __FILE__, line));
enforce(strideBack(RandomCU!dchar(s), i == size_t.max ? s.length : i) == codeLength!dchar(c),
new AssertError(format("Unit test failure range: %s", s), __FILE__, line));
auto refRandom = new RefRandomCU!dchar(s);
immutable randLen = refRandom.length;
enforce(strideBack(refRandom, i == size_t.max ? s.length : i) == codeLength!dchar(c),
new AssertError(format("Unit test failure rand ref range: %s", s), __FILE__, line));
enforce(refRandom.length == randLen,
new AssertError(format("Unit test failure rand ref range length: %s", s), __FILE__, line));
if (i == size_t.max)
{
enforce(strideBack(s) == codeLength!dchar(c),
new AssertError(format("Unit test failure string code length: %s", s), __FILE__, line));
enforce(strideBack(BidirCU!dchar(s)) == codeLength!dchar(c),
new AssertError(format("Unit test failure range code length: %s", s), __FILE__, line));
auto refBidir = new RefBidirCU!dchar(s);
immutable bidirLen = refBidir.length;
enforce(strideBack(refBidir) == codeLength!dchar(c),
new AssertError(format("Unit test failure bidir ref range code length: %s", s), __FILE__, line));
enforce(refBidir.length == bidirLen,
new AssertError(format("Unit test failure bidir ref range length: %s", s), __FILE__, line));