-
-
Notifications
You must be signed in to change notification settings - Fork 707
/
Copy pathstring.d
7318 lines (6425 loc) · 219 KB
/
string.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.
/**
String handling functions.
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE ,
$(TR $(TH Category) $(TH Functions) )
$(TR $(TDNW Searching)
$(TD
$(MYREF column)
$(MYREF indexOf)
$(MYREF indexOfAny)
$(MYREF indexOfNeither)
$(MYREF lastIndexOf)
$(MYREF lastIndexOfAny)
$(MYREF lastIndexOfNeither)
)
)
$(TR $(TDNW Comparison)
$(TD
$(MYREF isNumeric)
)
)
$(TR $(TDNW Mutation)
$(TD
$(MYREF capitalize)
)
)
$(TR $(TDNW Pruning and Filling)
$(TD
$(MYREF center)
$(MYREF chomp)
$(MYREF chompPrefix)
$(MYREF chop)
$(MYREF detabber)
$(MYREF detab)
$(MYREF entab)
$(MYREF entabber)
$(MYREF leftJustify)
$(MYREF outdent)
$(MYREF rightJustify)
$(MYREF strip)
$(MYREF stripLeft)
$(MYREF stripRight)
$(MYREF wrap)
)
)
$(TR $(TDNW Substitution)
$(TD
$(MYREF abbrev)
$(MYREF soundex)
$(MYREF soundexer)
$(MYREF succ)
$(MYREF tr)
$(MYREF translate)
)
)
$(TR $(TDNW Miscellaneous)
$(TD
$(MYREF assumeUTF)
$(MYREF fromStringz)
$(MYREF lineSplitter)
$(MYREF representation)
$(MYREF splitLines)
$(MYREF toStringz)
)
)))
Objects of types `string`, `wstring`, and `dstring` are value types
and cannot be mutated element-by-element. For using mutation during building
strings, use `char[]`, `wchar[]`, or `dchar[]`. The `xxxstring`
types are preferable because they don't exhibit undesired aliasing, thus
making code more robust.
The following functions are publicly imported:
$(BOOKTABLE ,
$(TR $(TH Module) $(TH Functions) )
$(LEADINGROW Publicly imported functions)
$(TR $(TD std.algorithm)
$(TD
$(REF_SHORT cmp, std,algorithm,comparison)
$(REF_SHORT count, std,algorithm,searching)
$(REF_SHORT endsWith, std,algorithm,searching)
$(REF_SHORT startsWith, std,algorithm,searching)
))
$(TR $(TD std.array)
$(TD
$(REF_SHORT join, std,array)
$(REF_SHORT replace, std,array)
$(REF_SHORT replaceInPlace, std,array)
$(REF_SHORT split, std,array)
$(REF_SHORT empty, std,array)
))
$(TR $(TD std.format)
$(TD
$(REF_SHORT format, std,format)
$(REF_SHORT sformat, std,format)
))
$(TR $(TD std.uni)
$(TD
$(REF_SHORT icmp, std,uni)
$(REF_SHORT toLower, std,uni)
$(REF_SHORT toLowerInPlace, std,uni)
$(REF_SHORT toUpper, std,uni)
$(REF_SHORT toUpperInPlace, std,uni)
))
)
There is a rich set of functions for string handling defined in other modules.
Functions related to Unicode and ASCII are found in $(MREF std, uni)
and $(MREF std, ascii), respectively. Other functions that have a
wider generality than just strings can be found in $(MREF std, algorithm)
and $(MREF std, range).
See_Also:
$(LIST
$(MREF std, algorithm) and
$(MREF std, range)
for generic range algorithms
,
$(MREF std, ascii)
for functions that work with ASCII strings
,
$(MREF std, uni)
for functions that work with unicode strings
)
Copyright: Copyright The D Language Foundation 2007-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP digitalmars.com, Walter Bright),
$(HTTP erdani.org, Andrei Alexandrescu),
$(HTTP jmdavisprog.com, Jonathan M Davis),
and David L. 'SpottedTiger' Davis
Source: $(PHOBOSSRC std/string.d)
*/
module std.string;
version (StdUnittest)
{
private:
struct TestAliasedString
{
string get() @safe @nogc pure nothrow return scope { return _s; }
alias get this;
@disable this(this);
string _s;
}
bool testAliasedString(alias func, Args...)(string s, Args args)
{
import std.algorithm.comparison : equal;
auto a = func(TestAliasedString(s), args);
auto b = func(s, args);
static if (is(typeof(equal(a, b))))
{
// For ranges, compare contents instead of object identity.
return equal(a, b);
}
else
{
return a == b;
}
}
}
public import std.format : format, sformat;
import std.typecons : Flag, Yes, No;
public import std.uni : icmp, toLower, toLowerInPlace, toUpper, toUpperInPlace;
import std.meta : AliasSeq, staticIndexOf;
import std.range.primitives : back, ElementEncodingType, ElementType, front,
hasLength, hasSlicing, isBidirectionalRange, isForwardRange, isInfinite,
isInputRange, isOutputRange, isRandomAccessRange, popBack, popFront, put,
save;
import std.traits : isConvertibleToString, isNarrowString, isSomeChar,
isSomeString, StringTypeOf, Unqual;
//public imports for backward compatibility
public import std.algorithm.comparison : cmp;
public import std.algorithm.searching : startsWith, endsWith, count;
public import std.array : join, replace, replaceInPlace, split, empty;
/* ************* Exceptions *************** */
/++
Exception thrown on errors in std.string functions.
+/
class StringException : Exception
{
import std.exception : basicExceptionCtors;
///
mixin basicExceptionCtors;
}
///
@safe pure unittest
{
import std.exception : assertThrown;
auto bad = " a\n\tb\n c";
assertThrown!StringException(bad.outdent);
}
/++
Params:
cString = A null-terminated c-style string.
Returns: A D-style array of `char`, `wchar` or `dchar` referencing the same
string. The returned array will retain the same type qualifiers as the input.
$(RED Important Note:) The returned array is a slice of the original buffer.
The original data is not changed and not copied.
+/
inout(Char)[] fromStringz(Char)(return scope inout(Char)* cString) @nogc @system pure nothrow
if (isSomeChar!Char)
{
import core.stdc.stddef : wchar_t;
static if (is(immutable Char == immutable char))
import core.stdc.string : cstrlen = strlen;
else static if (is(immutable Char == immutable wchar_t))
import core.stdc.wchar_ : cstrlen = wcslen;
else
static size_t cstrlen(scope const Char* s)
{
const(Char)* p = s;
while (*p)
++p;
return p - s;
}
return cString ? cString[0 .. cstrlen(cString)] : null;
}
/// ditto
inout(Char)[] fromStringz(Char)(return scope inout(Char)[] cString) @nogc @safe pure nothrow
if (isSomeChar!Char)
{
foreach (i; 0 .. cString.length)
if (cString[i] == '\0')
return cString[0 .. i];
return cString;
}
///
@system pure unittest
{
assert(fromStringz("foo\0"c.ptr) == "foo"c);
assert(fromStringz("foo\0"w.ptr) == "foo"w);
assert(fromStringz("foo\0"d.ptr) == "foo"d);
assert(fromStringz("福\0"c.ptr) == "福"c);
assert(fromStringz("福\0"w.ptr) == "福"w);
assert(fromStringz("福\0"d.ptr) == "福"d);
}
///
@nogc @safe pure nothrow unittest
{
struct C
{
char[32] name;
}
assert(C("foo\0"c).name.fromStringz() == "foo"c);
struct W
{
wchar[32] name;
}
assert(W("foo\0"w).name.fromStringz() == "foo"w);
struct D
{
dchar[32] name;
}
assert(D("foo\0"d).name.fromStringz() == "foo"d);
}
@nogc @safe pure nothrow unittest
{
assert( string.init.fromStringz() == ""c);
assert(wstring.init.fromStringz() == ""w);
assert(dstring.init.fromStringz() == ""d);
immutable char[3] a = "foo"c;
assert(a.fromStringz() == "foo"c);
immutable wchar[3] b = "foo"w;
assert(b.fromStringz() == "foo"w);
immutable dchar[3] c = "foo"d;
assert(c.fromStringz() == "foo"d);
}
@system pure unittest
{
char* a = null;
assert(fromStringz(a) == null);
wchar* b = null;
assert(fromStringz(b) == null);
dchar* c = null;
assert(fromStringz(c) == null);
const char* d = "foo\0";
assert(fromStringz(d) == "foo");
immutable char* e = "foo\0";
assert(fromStringz(e) == "foo");
const wchar* f = "foo\0";
assert(fromStringz(f) == "foo");
immutable wchar* g = "foo\0";
assert(fromStringz(g) == "foo");
const dchar* h = "foo\0";
assert(fromStringz(h) == "foo");
immutable dchar* i = "foo\0";
assert(fromStringz(i) == "foo");
immutable wchar z = 0x0000;
// Test some surrogate pairs
// high surrogates are in the range 0xD800 .. 0xDC00
// low surrogates are in the range 0xDC00 .. 0xE000
// since UTF16 doesn't specify endianness we test both.
foreach (wchar[] t; [[0xD800, 0xDC00], [0xD800, 0xE000], [0xDC00, 0xDC00],
[0xDC00, 0xE000], [0xDA00, 0xDE00]])
{
immutable hi = t[0], lo = t[1];
assert(fromStringz([hi, lo, z].ptr) == [hi, lo]);
assert(fromStringz([lo, hi, z].ptr) == [lo, hi]);
}
}
/++
Params:
s = A D-style string.
Returns: A C-style null-terminated string equivalent to `s`. `s`
must not contain embedded `'\0'`'s as any C function will treat the
first `'\0'` that it sees as the end of the string. If `s.empty` is
`true`, then a string containing only `'\0'` is returned.
$(RED Important Note:) When passing a `char*` to a C function, and the C
function keeps it around for any reason, make sure that you keep a
reference to it in your D code. Otherwise, it may become invalid during a
garbage collection cycle and cause a nasty bug when the C code tries to use
it.
+/
immutable(char)* toStringz(scope const(char)[] s) @trusted pure nothrow
out (result)
{
import core.stdc.string : strlen, memcmp;
if (result)
{
auto slen = s.length;
while (slen > 0 && s[slen-1] == 0) --slen;
assert(strlen(result) == slen,
"The result c string is shorter than the in input string");
assert(result[0 .. slen] == s[0 .. slen],
"The input and result string are not equal");
}
}
do
{
import std.exception : assumeUnique;
if (s.empty) return "".ptr;
/+ Unfortunately, this isn't reliable.
We could make this work if string literals are put
in read-only memory and we test if s[] is pointing into
that.
/* Peek past end of s[], if it's 0, no conversion necessary.
* Note that the compiler will put a 0 past the end of static
* strings, and the storage allocator will put a 0 past the end
* of newly allocated char[]'s.
*/
char* p = &s[0] + s.length;
if (*p == 0)
return s;
+/
// Need to make a copy
auto copy = new char[s.length + 1];
copy[0 .. s.length] = s[];
copy[s.length] = 0;
return &assumeUnique(copy)[0];
}
///
pure nothrow @system unittest
{
import core.stdc.string : strlen;
import std.conv : to;
auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
assert(strlen(p) == 2);
string test = "";
p = toStringz(test);
assert(*p == 0);
test = "\0";
p = toStringz(test);
assert(*p == 0);
test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);
const string test2 = "";
p = toStringz(test2);
assert(*p == 0);
assert(toStringz([]) is toStringz(""));
}
pure nothrow @system unittest // https://issues.dlang.org/show_bug.cgi?id=15136
{
static struct S
{
immutable char[5] str;
ubyte foo;
this(char[5] str) pure nothrow
{
this.str = str;
}
}
auto s = S("01234");
const str = s.str.toStringz;
assert(str !is s.str.ptr);
assert(*(str + 5) == 0); // Null terminated.
s.foo = 42;
assert(*(str + 5) == 0); // Still null terminated.
}
/**
Flag indicating whether a search is case-sensitive.
*/
alias CaseSensitive = Flag!"caseSensitive";
/++
Searches for a character in a string or range.
Params:
s = string or InputRange of characters to search for `c` in
c = character to search for in `s`
startIdx = index to a well-formed code point in `s` to start
searching from; defaults to 0
cs = specifies whether comparisons are case-sensitive
(`Yes.caseSensitive`) or not (`No.caseSensitive`).
Returns:
If `c` is found in `s`, then the index of its first occurrence is
returned. If `c` is not found or `startIdx` is greater than or equal to
`s.length`, then -1 is returned. If the parameters are not valid UTF,
the result will still be either -1 or in the range [`startIdx` ..
`s.length`], but will not be reliable otherwise.
Throws:
If the sequence starting at `startIdx` does not represent a well-formed
code point, then a $(REF UTFException, std,utf) may be thrown.
See_Also: $(REF countUntil, std,algorithm,searching)
+/
ptrdiff_t indexOf(Range)(Range s, dchar c, CaseSensitive cs = Yes.caseSensitive)
if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)
{
return _indexOf(s, c, cs);
}
/// Ditto
ptrdiff_t indexOf(C)(scope const(C)[] s, dchar c, CaseSensitive cs = Yes.caseSensitive)
if (isSomeChar!C)
{
return _indexOf(s, c, cs);
}
/// Ditto
ptrdiff_t indexOf(Range)(Range s, dchar c, size_t startIdx, CaseSensitive cs = Yes.caseSensitive)
if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)
{
return _indexOf(s, c, startIdx, cs);
}
/// Ditto
ptrdiff_t indexOf(C)(scope const(C)[] s, dchar c, size_t startIdx, CaseSensitive cs = Yes.caseSensitive)
if (isSomeChar!C)
{
return _indexOf(s, c, startIdx, cs);
}
///
@safe pure unittest
{
import std.typecons : No;
string s = "Hello World";
assert(indexOf(s, 'W') == 6);
assert(indexOf(s, 'Z') == -1);
assert(indexOf(s, 'w', No.caseSensitive) == 6);
}
///
@safe pure unittest
{
import std.typecons : No;
string s = "Hello World";
assert(indexOf(s, 'W', 4) == 6);
assert(indexOf(s, 'Z', 100) == -1);
assert(indexOf(s, 'w', 3, No.caseSensitive) == 6);
}
@safe pure unittest
{
assert(testAliasedString!indexOf("std/string.d", '/'));
enum S : string { a = "std/string.d" }
assert(S.a.indexOf('/') == 3);
char[S.a.length] sa = S.a[];
assert(sa.indexOf('/') == 3);
}
@safe pure unittest
{
import std.conv : to;
import std.exception : assertCTFEable;
import std.traits : EnumMembers;
import std.utf : byChar, byWchar, byDchar;
assertCTFEable!(
{
static foreach (S; AliasSeq!(string, wstring, dstring))
{{
assert(indexOf(cast(S) null, cast(dchar)'a') == -1);
assert(indexOf(to!S("def"), cast(dchar)'a') == -1);
assert(indexOf(to!S("abba"), cast(dchar)'a') == 0);
assert(indexOf(to!S("def"), cast(dchar)'f') == 2);
assert(indexOf(to!S("def"), cast(dchar)'a', No.caseSensitive) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', No.caseSensitive) == -1);
assert(indexOf(to!S("Abba"), cast(dchar)'a', No.caseSensitive) == 0);
assert(indexOf(to!S("def"), cast(dchar)'F', No.caseSensitive) == 2);
assert(indexOf(to!S("ödef"), 'ö', No.caseSensitive) == 0);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
assert(indexOf("def", cast(char)'f', No.caseSensitive) == 2);
assert(indexOf(sPlts, cast(char)'P', No.caseSensitive) == 23);
assert(indexOf(sPlts, cast(char)'R', No.caseSensitive) == 2);
}}
foreach (cs; EnumMembers!CaseSensitive)
{
assert(indexOf("hello\U00010143\u0100\U00010143", '\u0100', cs) == 9);
assert(indexOf("hello\U00010143\u0100\U00010143"w, '\u0100', cs) == 7);
assert(indexOf("hello\U00010143\u0100\U00010143"d, '\u0100', cs) == 6);
assert(indexOf("hello\U00010143\u0100\U00010143".byChar, '\u0100', cs) == 9);
assert(indexOf("hello\U00010143\u0100\U00010143".byWchar, '\u0100', cs) == 7);
assert(indexOf("hello\U00010143\u0100\U00010143".byDchar, '\u0100', cs) == 6);
assert(indexOf("hello\U000007FF\u0100\U00010143".byChar, 'l', cs) == 2);
assert(indexOf("hello\U000007FF\u0100\U00010143".byChar, '\u0100', cs) == 7);
assert(indexOf("hello\U0000EFFF\u0100\U00010143".byChar, '\u0100', cs) == 8);
assert(indexOf("hello\U00010100".byWchar, '\U00010100', cs) == 5);
assert(indexOf("hello\U00010100".byWchar, '\U00010101', cs) == -1);
}
char[10] fixedSizeArray = "0123456789";
assert(indexOf(fixedSizeArray, '2') == 2);
});
}
@safe pure unittest
{
assert(testAliasedString!indexOf("std/string.d", '/', 0));
assert(testAliasedString!indexOf("std/string.d", '/', 1));
assert(testAliasedString!indexOf("std/string.d", '/', 4));
enum S : string { a = "std/string.d" }
assert(S.a.indexOf('/', 0) == 3);
assert(S.a.indexOf('/', 1) == 3);
assert(S.a.indexOf('/', 4) == -1);
char[S.a.length] sa = S.a[];
assert(sa.indexOf('/', 0) == 3);
assert(sa.indexOf('/', 1) == 3);
assert(sa.indexOf('/', 4) == -1);
}
@safe pure unittest
{
import std.conv : to;
import std.traits : EnumMembers;
import std.utf : byCodeUnit, byChar, byWchar;
assert("hello".byCodeUnit.indexOf(cast(dchar)'l', 1) == 2);
assert("hello".byWchar.indexOf(cast(dchar)'l', 1) == 2);
assert("hello".byWchar.indexOf(cast(dchar)'l', 6) == -1);
static foreach (S; AliasSeq!(string, wstring, dstring))
{{
assert(indexOf(cast(S) null, cast(dchar)'a', 1) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', 1) == -1);
assert(indexOf(to!S("abba"), cast(dchar)'a', 1) == 3);
assert(indexOf(to!S("def"), cast(dchar)'f', 1) == 2);
assert((to!S("def")).indexOf(cast(dchar)'a', 1,
No.caseSensitive) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', 1,
No.caseSensitive) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', 12,
No.caseSensitive) == -1);
assert(indexOf(to!S("AbbA"), cast(dchar)'a', 2,
No.caseSensitive) == 3);
assert(indexOf(to!S("def"), cast(dchar)'F', 2, No.caseSensitive) == 2);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
assert(indexOf("def", cast(char)'f', cast(uint) 2,
No.caseSensitive) == 2);
assert(indexOf(sPlts, cast(char)'P', 12, No.caseSensitive) == 23);
assert(indexOf(sPlts, cast(char)'R', cast(ulong) 1,
No.caseSensitive) == 2);
}}
foreach (cs; EnumMembers!CaseSensitive)
{
assert(indexOf("hello\U00010143\u0100\U00010143", '\u0100', 2, cs)
== 9);
assert(indexOf("hello\U00010143\u0100\U00010143"w, '\u0100', 3, cs)
== 7);
assert(indexOf("hello\U00010143\u0100\U00010143"d, '\u0100', 6, cs)
== 6);
}
}
private ptrdiff_t _indexOf(Range)(Range s, dchar c, CaseSensitive cs = Yes.caseSensitive)
if (isInputRange!Range && isSomeChar!(ElementType!Range))
{
static import std.ascii;
static import std.uni;
import std.utf : byDchar, byCodeUnit, UTFException, codeLength;
alias Char = Unqual!(ElementEncodingType!Range);
if (cs == Yes.caseSensitive)
{
static if (Char.sizeof == 1 && isSomeString!Range)
{
if (std.ascii.isASCII(c) && !__ctfe)
{ // Plain old ASCII
static ptrdiff_t trustedmemchr(Range s, char c) @trusted
{
import core.stdc.string : memchr;
const p = cast(const(Char)*)memchr(s.ptr, c, s.length);
return p ? p - s.ptr : -1;
}
return trustedmemchr(s, cast(char) c);
}
}
static if (Char.sizeof == 1)
{
if (c <= 0x7F)
{
ptrdiff_t i;
foreach (const c2; s)
{
if (c == c2)
return i;
++i;
}
}
else
{
ptrdiff_t i;
foreach (const c2; s.byDchar())
{
if (c == c2)
return i;
i += codeLength!Char(c2);
}
}
}
else static if (Char.sizeof == 2)
{
if (c <= 0xFFFF)
{
ptrdiff_t i;
foreach (const c2; s)
{
if (c == c2)
return i;
++i;
}
}
else if (c <= 0x10FFFF)
{
// Encode UTF-16 surrogate pair
const wchar c1 = cast(wchar)((((c - 0x10000) >> 10) & 0x3FF) + 0xD800);
const wchar c2 = cast(wchar)(((c - 0x10000) & 0x3FF) + 0xDC00);
ptrdiff_t i;
for (auto r = s.byCodeUnit(); !r.empty; r.popFront())
{
if (c1 == r.front)
{
r.popFront();
if (r.empty) // invalid UTF - missing second of pair
break;
if (c2 == r.front)
return i;
++i;
}
++i;
}
}
}
else static if (Char.sizeof == 4)
{
ptrdiff_t i;
foreach (const c2; s)
{
if (c == c2)
return i;
++i;
}
}
else
static assert(0);
return -1;
}
else
{
if (std.ascii.isASCII(c))
{ // Plain old ASCII
immutable c1 = cast(char) std.ascii.toLower(c);
ptrdiff_t i;
foreach (const c2; s.byCodeUnit())
{
if (c1 == std.ascii.toLower(c2))
return i;
++i;
}
}
else
{ // c is a universal character
immutable c1 = std.uni.toLower(c);
ptrdiff_t i;
foreach (const c2; s.byDchar())
{
if (c1 == std.uni.toLower(c2))
return i;
i += codeLength!Char(c2);
}
}
}
return -1;
}
private ptrdiff_t _indexOf(Range)(Range s, dchar c, size_t startIdx, CaseSensitive cs = Yes.caseSensitive)
if (isInputRange!Range && isSomeChar!(ElementType!Range))
{
static if (isSomeString!(typeof(s)) ||
(hasSlicing!(typeof(s)) && hasLength!(typeof(s))))
{
if (startIdx < s.length)
{
ptrdiff_t foundIdx = indexOf(s[startIdx .. $], c, cs);
if (foundIdx != -1)
{
return foundIdx + cast(ptrdiff_t) startIdx;
}
}
}
else
{
foreach (i; 0 .. startIdx)
{
if (s.empty)
return -1;
s.popFront();
}
ptrdiff_t foundIdx = indexOf(s, c, cs);
if (foundIdx != -1)
{
return foundIdx + cast(ptrdiff_t) startIdx;
}
}
return -1;
}
private template _indexOfStr(CaseSensitive cs)
{
private ptrdiff_t _indexOfStr(Range, Char)(Range s, const(Char)[] sub)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) &&
isSomeChar!Char)
{
alias Char1 = Unqual!(ElementEncodingType!Range);
static if (isSomeString!Range)
{
static if (is(Char1 == Char) && cs == Yes.caseSensitive)
{
import std.algorithm.searching : countUntil;
return s.representation.countUntil(sub.representation);
}
else
{
import std.algorithm.searching : find;
const(Char1)[] balance;
static if (cs == Yes.caseSensitive)
{
balance = find(s, sub);
}
else
{
balance = find!
((a, b) => toLower(a) == toLower(b))
(s, sub);
}
return () @trusted { return balance.empty ? -1 : balance.ptr - s.ptr; } ();
}
}
else
{
if (s.empty)
return -1;
if (sub.empty)
return 0; // degenerate case
import std.utf : byDchar, codeLength;
auto subr = sub.byDchar; // decode sub[] by dchar's
dchar sub0 = subr.front; // cache first character of sub[]
subr.popFront();
// Special case for single character search
if (subr.empty)
return indexOf(s, sub0, cs);
static if (cs == No.caseSensitive)
sub0 = toLower(sub0);
/* Classic double nested loop search algorithm
*/
ptrdiff_t index = 0; // count code unit index into s
for (auto sbydchar = s.byDchar(); !sbydchar.empty; sbydchar.popFront())
{
dchar c2 = sbydchar.front;
static if (cs == No.caseSensitive)
c2 = toLower(c2);
if (c2 == sub0)
{
auto s2 = sbydchar.save; // why s must be a forward range
foreach (c; subr.save)
{
s2.popFront();
if (s2.empty)
return -1;
static if (cs == Yes.caseSensitive)
{
if (c != s2.front)
goto Lnext;
}
else
{
if (toLower(c) != toLower(s2.front))
goto Lnext;
}
}
return index;
}
Lnext:
index += codeLength!Char1(c2);
}
return -1;
}
}
}
/++
Searches for a substring in a string or range.
Params:
s = string or ForwardRange of characters to search for `sub` in
sub = substring to search for in `s`
startIdx = index to a well-formed code point in `s` to start
searching from; defaults to 0
cs = specifies whether comparisons are case-sensitive
(`Yes.caseSensitive`) or not (`No.caseSensitive`)
Returns:
The index of the first occurrence of `sub` in `s`. If `sub` is not found
or `startIdx` is greater than or equal to `s.length`, then -1 is
returned. If the arguments are not valid UTF, the result will still be
either -1 or in the range [`startIdx` .. `s.length`], but will not be
reliable otherwise.
Throws:
If the sequence starting at `startIdx` does not represent a well-formed
code point, then a $(REF UTFException, std,utf) may be thrown.
Bugs:
Does not work with case-insensitive strings where the mapping of
$(REF toLower, std,uni) and $(REF toUpper, std,uni) is not 1:1.
+/
ptrdiff_t indexOf(Range, Char)(Range s, const(Char)[] sub)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) &&
isSomeChar!Char)
{
return _indexOfStr!(Yes.caseSensitive)(s, sub);
}
/// Ditto
ptrdiff_t indexOf(Range, Char)(Range s, const(Char)[] sub, in CaseSensitive cs)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) &&
isSomeChar!Char)
{
if (cs == Yes.caseSensitive)
return indexOf(s, sub);
else
return _indexOfStr!(No.caseSensitive)(s, sub);
}
/// Ditto
ptrdiff_t indexOf(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub,
in size_t startIdx)
@safe
if (isSomeChar!Char1 && isSomeChar!Char2)
{
if (startIdx >= s.length)
return -1;
ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub);
if (foundIdx == -1)
return -1;
return foundIdx + cast(ptrdiff_t) startIdx;
}
/// Ditto
ptrdiff_t indexOf(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub,
in size_t startIdx, in CaseSensitive cs)
@safe
if (isSomeChar!Char1 && isSomeChar!Char2)
{
if (startIdx >= s.length)
return -1;
ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub, cs);
if (foundIdx == -1)
return -1;
return foundIdx + cast(ptrdiff_t) startIdx;
}
///
@safe pure unittest
{
import std.typecons : No;
string s = "Hello World";
assert(indexOf(s, "Wo", 4) == 6);
assert(indexOf(s, "Zo", 100) == -1);
assert(indexOf(s, "wo", 3, No.caseSensitive) == 6);
}
///
@safe pure unittest
{
import std.typecons : No;
string s = "Hello World";
assert(indexOf(s, "Wo") == 6);
assert(indexOf(s, "Zo") == -1);
assert(indexOf(s, "wO", No.caseSensitive) == 6);
}
@safe pure nothrow @nogc unittest
{
string s = "Hello World";
assert(indexOf(s, "Wo", 4) == 6);