-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.d
2100 lines (1907 loc) · 57.2 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
/++
+ String manipulation functions complementing the standard library, as well as
+ providing dumbed-down and optimised versions of existing functions therein.
+
+ Example:
+ ---
+ {
+ string line = "Lorem ipsum :sit amet";
+ immutable lorem = line.nom(" :");
+ assert(lorem == "Lorem ipsum", lorem);
+ assert(line == "sit amet", line);
+ }
+ {
+ string line = "Lorem ipsum :sit amet";
+ immutable lorem = line.nom(':');
+ assert(lorem == "Lorem ipsum ", lorem);
+ assert(line == "sit amet", line);
+ }
+ {
+ string line = "Lorem ipsum sit amet"; // mutable, will be modified by ref
+ string[] words;
+
+ while (line.length > 0)
+ {
+ immutable word = line.nom!(Yes.inherit)(" ");
+ words ~= word;
+ }
+
+ assert(words == [ "Lorem", "ipsum", "sit", "amet" ]);
+ }
+ ---
+/
module lu.string;
private:
import std.range.primitives : ElementEncodingType, ElementType, isOutputRange;
import std.traits : isIntegral, isMutable, isSomeString;
import std.typecons : Flag, No, Yes;
public:
@safe:
// nom
/++
+ Given some string, finds the supplied needle token in it, returns the
+ string up to that point, and advances the passed string by ref to after the token.
+
+ The naming is in line with standard library functions such as
+ `std.string.munch`, `std.file.slurp` and others.
+
+ Example:
+ ---
+ string foobar = "foo bar!";
+ string foo = foobar.nom(" ");
+ string bar = foobar.nom("!");
+
+ assert((foo == "foo"), foo);
+ assert((bar == "bar"), bar);
+ assert(!foobar.length);
+
+ enum line = "abc def ghi";
+ string def = line[4..$].nom(" "); // now with auto ref
+ ---
+
+ Params:
+ decode = Whether to use auto-decoding functions, or try to keep to non-
+ decoding ones (whenever possible).
+ haystack = String to walk and advance.
+ needle = Token that deliminates what should be returned and to where to advance.
+ callingFile = Name of the calling source file, used to pass along when
+ throwing an exception.
+ callingLine = Line number where in the source file this is called, used
+ to pass along when throwing an exception.
+
+ Returns:
+ The string `haystack` from the start up to the needle token. The original
+ variable is advanced to after the token.
+
+ Throws:
+ `lu.string.NomException` if the needle could not be found in the string.
+/
pragma(inline)
T nom(Flag!"decode" decode = No.decode, T, C)(auto ref T haystack, const C needle,
const string callingFile = __FILE__, const size_t callingLine = __LINE__) pure @nogc
if (isMutable!T && isSomeString!T && (is(C : T) || is(C : ElementType!T) || is(C : ElementEncodingType!T)))
in
{
static if (__traits(compiles, needle.length))
{
assert(needle.length, "Tried to `nom` with no `needle` given");
}
}
do
{
static if (decode || is(T : dstring) || is(T : wstring))
{
import std.string : indexOf;
// dstring and wstring only work with indexOf, not countUntil
immutable index = haystack.indexOf(needle);
}
else
{
// Only do this if we know it's not user text
import std.algorithm.searching : countUntil;
import std.string : representation;
static if (isSomeString!C)
{
immutable index = haystack.representation.countUntil(needle.representation);
}
else
{
immutable index = haystack.representation.countUntil(cast(ubyte)needle);
}
}
if (index == -1)
{
throw new NomExceptionImpl!(T, C)("Tried to nom too much",
haystack, needle, callingFile, callingLine);
}
static if (isSomeString!C)
{
immutable separatorLength = needle.length;
}
else
{
enum separatorLength = 1;
}
static if (__traits(isRef, haystack))
{
scope(exit) haystack = haystack[(index+separatorLength)..$];
}
return haystack[0..index];
}
///
unittest
{
import std.conv : to;
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom(" :");
assert(lorem == "Lorem ipsum", lorem);
assert(line == "sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom!(Yes.decode)(" :");
assert(lorem == "Lorem ipsum", lorem);
assert(line == "sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom(':');
assert(lorem == "Lorem ipsum ", lorem);
assert(line == "sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom!(Yes.decode)(':');
assert(lorem == "Lorem ipsum ", lorem);
assert(line == "sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom(' ');
assert(lorem == "Lorem", lorem);
assert(line == "ipsum :sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom!(Yes.decode)(' ');
assert(lorem == "Lorem", lorem);
assert(line == "ipsum :sit amet", line);
}
/*{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom("");
assert(!lorem.length, lorem);
assert(line == "Lorem ipsum :sit amet", line);
}*/
/*{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom!(Yes.decode)("");
assert(!lorem.length, lorem);
assert(line == "Lorem ipsum :sit amet", line);
}*/
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom("Lorem ipsum");
assert(!lorem.length, lorem);
assert(line == " :sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable lorem = line.nom!(Yes.decode)("Lorem ipsum");
assert(!lorem.length, lorem);
assert(line == " :sit amet", line);
}
{
string line = "Lorem ipsum :sit amet";
immutable dchar dspace = ' ';
immutable lorem = line.nom(dspace);
assert(lorem == "Lorem", lorem);
assert(line == "ipsum :sit amet", line);
}
{
dstring dline = "Lorem ipsum :sit amet"d;
immutable dspace = " "d;
immutable lorem = dline.nom(dspace);
assert((lorem == "Lorem"d), lorem.to!string);
assert((dline == "ipsum :sit amet"d), dline.to!string);
}
{
dstring dline = "Lorem ipsum :sit amet"d;
immutable wchar wspace = ' ';
immutable lorem = dline.nom(wspace);
assert((lorem == "Lorem"d), lorem.to!string);
assert((dline == "ipsum :sit amet"d), dline.to!string);
}
{
wstring wline = "Lorem ipsum :sit amet"w;
immutable wchar wspace = ' ';
immutable lorem = wline.nom(wspace);
assert((lorem == "Lorem"w), lorem.to!string);
assert((wline == "ipsum :sit amet"w), wline.to!string);
}
{
wstring wline = "Lorem ipsum :sit amet"w;
immutable wspace = " "w;
immutable lorem = wline.nom(wspace);
assert((lorem == "Lorem"w), lorem.to!string);
assert((wline == "ipsum :sit amet"w), wline.to!string);
}
{
string user = "foo!bar@asdf.adsf.com";
user = user.nom('!');
assert((user == "foo"), user);
}
{
immutable def = "abc def ghi"[4..$].nom(" ");
assert((def == "def"), def);
}
}
// nom
/++
+ Given some string, finds the supplied needle token in it, returns the
+ string up to that point, and advances the passed string by ref to after the token.
+
+ The naming is in line with standard library functions such as
+ `std.string.munch`, `std.file.slurp` and others.
+
+ Overload that takes an extra `Flag!"inherit"` template parameter, to toggle
+ whether the return value inherits the passed line (and clearing it) upon no
+ needle match.
+
+ Example:
+ ---
+ string foobar = "foo bar!";
+ string foo = foobar.nom(" ");
+ string bar = foobar.nom!(Yes.inherit)("?");
+
+ assert((foo == "foo"), foo);
+ assert((bar == "bar!"), bar);
+ assert(!foobar.length);
+
+ string slice = "snarfl";
+ string verb = slice.nom!(Yes.inherit)(" ");
+
+ assert((verb == "snarfl"), verb);
+ assert(!slice.length, slice);
+ ---
+
+ Params:
+ inherit = Whether or not to have the returned string inherit (and clear)
+ the passed haystack by ref.
+ decode = Whether to use auto-decoding functions, or try to keep to non-
+ decoding ones (when possible).
+ haystack = String to walk and advance.
+ needle = Token that deliminates what should be returned and to where to advance.
+ callingFile = Name of the calling source file, used to pass along when
+ throwing an exception.
+ callingLine = Line number where in the source file this is called, used
+ to pass along when throwing an exception.
+
+ Returns:
+ The string `haystack` from the start up to the needle token, if it exists.
+ If so, the original variable is advanced to after the token.
+ If it doesn't exist, the string in `haystack` is inherited into the return
+ value and returned, while the `haystack` symbol itself is cleared.
+/
pragma(inline)
T nom(Flag!"inherit" inherit, Flag!"decode" decode = No.decode, T, C)
(ref T haystack, const C needle, const string callingFile = __FILE__,
const size_t callingLine = __LINE__) pure @nogc
if (isMutable!T && isSomeString!T && (is(C : T) || is(C : ElementType!T) || is(C : ElementEncodingType!T)))
in
{
static if (__traits(compiles, needle.length))
{
assert(needle.length, "Tried to `nom` with no `needle` given");
}
}
do
{
static if (inherit)
{
if (haystack.contains!decode(needle))
{
// Separator exists, no inheriting will take place, call original nom
return haystack.nom!decode(needle, callingFile, callingLine);
}
else
{
// No needle match; inherit string and clear the original
scope(exit) haystack = string.init;
return haystack;
}
}
else
{
// Not inheriting due to argument No.inherit, so just pass onto original nom
return haystack.nom!decode(needle, callingFile, callingLine);
}
}
///
unittest
{
{
string line = "Lorem ipsum";
immutable head = line.nom(" ");
assert((head == "Lorem"), head);
assert((line == "ipsum"), line);
}
{
string line = "Lorem";
immutable head = line.nom!(Yes.inherit)(" ");
assert((head == "Lorem"), head);
assert(!line.length, line);
}
{
string slice = "verb";
string verb;
if (slice.contains(' '))
{
verb = slice.nom(' ');
}
else
{
verb = slice;
slice = string.init;
}
assert((verb == "verb"), verb);
assert(!slice.length, slice);
}
{
string slice = "verb";
immutable verb = slice.nom!(Yes.inherit)(' ');
assert((verb == "verb"), verb);
assert(!slice.length, slice);
}
{
string url = "https://google.com/index.html#fragment-identifier";
url = url.nom!(Yes.inherit)('#');
assert((url == "https://google.com/index.html"), url);
}
{
string url = "https://google.com/index.html";
url = url.nom!(Yes.inherit)('#');
assert((url == "https://google.com/index.html"), url);
}
{
string line = "Lorem ipsum sit amet";
string[] words;
while (line.length > 0)
{
immutable word = line.nom!(Yes.inherit)(" ");
words ~= word;
}
assert(words == [ "Lorem", "ipsum", "sit", "amet" ]);
}
}
// NomException
/++
+ Exception, to be thrown when a call to `nom` went wrong.
+
+ It is a normal `object.Exception` but with an attached needle and haystack.
+/
abstract class NomException : Exception
{
/// Returns a string of the original haystack the call to `nom` was operating on.
string haystack();
/// Returns a string of the original needle the call to `nom` was operating on.
string needle();
/// Create a new `NomExceptionImpl`, without attaching anything.
this(const string message, const string file = __FILE__, const size_t line = __LINE__) pure @nogc
{
super(message, file, line);
}
}
// NomExceptionImpl
/++
+ Exception, to be thrown when a call to `nom` went wrong.
+
+ This is the templated implementation, so that we can support more than one
+ kind of needle and haystack combination.
+
+ It is a normal `object.Exception` but with an attached needle and haystack.
+
+ Params:
+ T = Haystack type (`string`, `wstring` or `dstring`).
+ C = Needle type (any type of character or any string).
+/
final class NomExceptionImpl(T, C) : NomException
{
@safe:
/// Raw haystack that `haystack` converts to string and returns.
T rawHaystack;
/// Raw needle that `needle` converts to string and returns.
C rawNeedle;
/++
+ Returns a string of the original needle the call to `nom` was operating on.
+
+ Returns:
+ The raw haystack (be it any kind of string), converted to a `string`.
+/
override string haystack()
{
import std.conv : to;
return rawHaystack.to!string;
}
/++
+ Returns a string of the original needle the call to `nom` was operating on.
+
+ Returns:
+ The raw needle (be it any kind of string or character), converted to a `string`.
+/
override string needle()
{
import std.conv : to;
return rawNeedle.to!string;
}
/// Create a new `NomExceptionImpl`, without attaching anything.
this(const string message, const string file = __FILE__, const size_t line = __LINE__) pure @nogc
{
super(message, file, line);
}
/// Create a new `NomExceptionImpl`, attaching a command.
this(const string message, const T rawHaystack, const C rawNeedle,
const string file = __FILE__, const size_t line = __LINE__) pure @nogc
{
this.rawHaystack = rawHaystack;
this.rawNeedle = rawNeedle;
super(message, file, line);
}
}
// plurality
/++
+ Selects the correct singular or plural form of a word depending on the
+ numerical count of it.
+
+ Example:
+ ---
+ string one = 1.plurality("one", "two");
+ string two = 2.plurality("one", "two");
+ string many = (-2).plurality("one", "many");
+ string many0 = 0.plurality("one", "many");
+
+ assert((one == "one"), one);
+ assert((two == "two"), two);
+ assert((many == "many"), many);
+ assert((many0 == "many"), many0);
+ ---
+
+ Params:
+ num = Numerical count of the noun.
+ singular = The noun in singular form.
+ plural = The noun in plural form.
+
+ Returns:
+ The singular string if num is `1` or `-1`, otherwise the plural string.
+/
pragma(inline)
T plurality(Num, T)(const Num num, const T singular, const T plural) pure nothrow @nogc
if (isIntegral!Num && isSomeString!T)
{
return ((num == 1) || (num == -1)) ? singular : plural;
}
///
unittest
{
static assert(10.plurality("one","many") == "many");
static assert(1.plurality("one", "many") == "one");
static assert((-1).plurality("one", "many") == "one");
static assert(0.plurality("one", "many") == "many");
}
// unenclosed
/++
+ Removes paired preceding and trailing tokens around a string line.
+ Assumes ASCII.
+
+ You should not need to use this directly; rather see `unquoted` and `unsinglequoted`.
+
+ Params:
+ token = Token character to strip away.
+ line = String line to remove any enclosing tokens from.
+
+ Returns:
+ A slice of the passed string line without enclosing tokens.
+/
private T unenclosed(char token = '"', T)(const T line) pure nothrow @nogc
if (isSomeString!T)
{
enum escaped = "\\" ~ token;
if (line.length < 2)
{
return line;
}
else if ((line[0] == token) && (line[$-1] == token))
{
if ((line.length >= 3) && (line[$-2..$] == escaped))
{
// End quote is escaped
return line;
}
return line[1..$-1].unenclosed!token;
}
else
{
return line;
}
}
// unquoted
/++
+ Removes paired preceding and trailing double quotes, unquoting a word.
+ Assumes ASCII.
+
+ Does not decode the string and may thus give weird results on weird inputs.
+
+ Example:
+ ---
+ string quoted = `"This is a quote"`;
+ string unquotedLine = quoted.unquoted;
+ assert((unquotedLine == "This is a quote"), unquotedLine);
+ ---
+
+ Params:
+ line = The (potentially) quoted string.
+
+ Returns:
+ A slice of the `line` argument that excludes the quotes.
+/
pragma(inline)
T unquoted(T)(const T line) pure nothrow @nogc
{
return unenclosed!'"'(line);
}
///
unittest
{
assert(`"Lorem ipsum sit amet"`.unquoted == "Lorem ipsum sit amet");
assert(`"""""Lorem ipsum sit amet"""""`.unquoted == "Lorem ipsum sit amet");
// Unbalanced quotes are left untouched
assert(`"Lorem ipsum sit amet`.unquoted == `"Lorem ipsum sit amet`);
assert(`"Lorem \"`.unquoted == `"Lorem \"`);
assert("\"Lorem \\\"".unquoted == "\"Lorem \\\"");
assert(`"\"`.unquoted == `"\"`);
}
// unsinglequoted
/++
+ Removes paired preceding and trailing single quotes around a line.
+ Assumes ASCII.
+
+ Does not decode the string and may thus give weird results on weird inputs.
+
+ Example:
+ ---
+ string quoted = `'This is single-quoted'`;
+ string unquotedLine = quoted.unsinglequoted;
+ assert((unquotedLine == "This is single-quoted"), unquotedLine);
+ ---
+
+ Params:
+ line = The (potentially) single-quoted string.
+
+ Returns:
+ A slice of the `line` argument that excludes the single-quotes.
+/
pragma(inline)
T unsinglequoted(T)(const T line) pure nothrow @nogc
{
return unenclosed!'\''(line);
}
///
unittest
{
assert(`'Lorem ipsum sit amet'`.unsinglequoted == "Lorem ipsum sit amet");
assert(`''''Lorem ipsum sit amet''''`.unsinglequoted == "Lorem ipsum sit amet");
// Unbalanced quotes are left untouched
assert(`'Lorem ipsum sit amet`.unsinglequoted == `'Lorem ipsum sit amet`);
assert(`'Lorem \'`.unsinglequoted == `'Lorem \'`);
assert("'Lorem \\'".unsinglequoted == "'Lorem \\'");
assert(`'`.unsinglequoted == `'`);
}
// beginsWith
/++
+ A cheaper variant of `std.algorithm.searching.startsWith`, since this is
+ such a hotspot.
+
+ Merely slices; does not decode the string and may thus give weird results on
+ weird inputs.
+
+ Example:
+ ---
+ assert("Lorem ipsum sit amet".beginsWith("Lorem ip"));
+ assert(!"Lorem ipsum sit amet".beginsWith("ipsum sit amet"));
+ ---
+
+ Params:
+ haystack = Original line to examine.
+ needle = Snippet of text to check if `haystack` begins with.
+
+ Returns:
+ `true` if `haystack` begins with `needle`, `false` if not.
+/
pragma(inline)
bool beginsWith(T, C)(const T haystack, const C needle) pure nothrow @nogc
if (isSomeString!T && (is(C : T) || is(C : ElementType!T) || is(C : ElementEncodingType!T)))
{
static if (is(C : ElementEncodingType!T))
{
// Needle is never empty but haystack may be
return haystack.length && (haystack[0] == needle);
}
else
{
if (!needle.length)
{
return true;
}
else if ((needle.length > haystack.length) || !haystack.length)
{
return false;
}
if (haystack[0] != needle[0]) return false;
return (haystack[0..needle.length] == needle);
}
}
///
unittest
{
assert("Lorem ipsum sit amet".beginsWith("Lorem ip"));
assert(!"Lorem ipsum sit amet".beginsWith("ipsum sit amet"));
assert("Lorem ipsum sit amet".beginsWith(""));
assert("Lorem ipsum sit amet".beginsWith('L'));
assert(!"Lorem ipsum sit amet".beginsWith(char.init));
assert(!"".beginsWith("Harbl"));
assert(!"".beginsWith('c'));
assert("".beginsWith(""));
}
// beginsWithOneOf
/++
+ Checks whether or not the first letter of a string begins with any of the
+ passed string of characters, or single character.
+
+ Merely slices; does not decode the string and may thus give weird results on
+ weird inputs.
+
+ Params:
+ haystack = String to examine the start of, or single character.
+ needles = String of characters to look for in the start of `haystack`,
+ or a single character.
+
+ Returns:
+ `true` if the first character of `haystack` is also in `needles`,
+ `false` if not.
+/
pragma(inline)
bool beginsWithOneOf(T, C)(const T haystack, const C needles) pure nothrow @nogc
if (is(C : T) || is(C : ElementEncodingType!T) || is(T : ElementEncodingType!C))
{
import std.range.primitives : hasLength;
static if (is(C : T) && (isSomeString!T || hasLength!T))
{
version(Windows)
{
// Windows workaround for memchr segfault
// See https://forum.dlang.org/post/qgzznkhvvozadnagzudu@forum.dlang.org
if ((needles.ptr is null) || !needles.length) return true;
}
else
{
// All strings begin with an empty string
if (!needles.length) return true;
}
// An empty line begins with nothing
if (!haystack.length) return false;
return needles.contains(haystack[0]);
}
else static if (is(C : ElementEncodingType!T))
{
// T is a string, C is a char
return haystack[0] == needles;
}
else static if (is(T : ElementEncodingType!C))
{
// T is a char, C is a string
return needles.length ? needles.contains(haystack) : true;
}
else
{
import std.format : format;
static assert(0, "Unexpected types passed to `beginWithOneOf`: `%s` and `%s`"
.format(T.stringof, C.stringof));
}
}
///
unittest
{
assert("#channel".beginsWithOneOf("#%+"));
assert(!"#channel".beginsWithOneOf("~%+"));
assert("".beginsWithOneOf(""));
assert("abc".beginsWithOneOf(string.init));
assert(!"".beginsWithOneOf("abc"));
assert("abc".beginsWithOneOf('a'));
assert(!"abc".beginsWithOneOf('b'));
assert(!"abc".beginsWithOneOf(char.init));
assert('#'.beginsWithOneOf("#%+"));
assert(!'#'.beginsWithOneOf("~%+"));
assert('a'.beginsWithOneOf(string.init));
assert(!'d'.beginsWithOneOf("abc"));
}
// stripSuffix
/++
+ Strips the supplied string from the end of a string.
+
+ Example:
+ ---
+ string suffixed = "Kameloso";
+ string stripped = suffixed.stripSuffix("oso");
+ assert((stripped == "Kamel"), stripped);
+ ---
+
+ Params:
+ line = Original line to strip the suffix from.
+ suffix = Suffix string to strip.
+
+ Returns:
+ `line` with `suffix` sliced off the end.
+/
string stripSuffix(const string line, const string suffix) pure nothrow @nogc
{
if (line.length < suffix.length) return line;
return (line[($-suffix.length)..$] == suffix) ? line[0..($-suffix.length)] : line;
}
///
unittest
{
immutable line = "harblsnarbl";
assert(line.stripSuffix("snarbl") == "harbl");
assert(line.stripSuffix("") == "harblsnarbl");
assert(line.stripSuffix("INVALID") == "harblsnarbl");
assert(!line.stripSuffix("harblsnarbl").length);
}
// tabs
/++
+ Returns a range of *spaces* equal to that of `num` tabs (\t).
+
+ Use `std.conv.to` or `std.conv.text` or similar to flatten to a string.
+
+ Example:
+ ---
+ string indentation = 2.tabs.text;
+ assert((indentation == " "), `"` ~ indentation ~ `"`);
+ string smallIndent = 1.tabs!2.text;
+ assert((smallIndent == " "), `"` ~ smallIndent ~ `"`);
+ ---
+
+ Params:
+ spaces = How many spaces make up a tab.
+ num = How many tabs we want.
+
+ Returns:
+ Whitespace equalling (`num` * `spaces`) spaces.
+/
auto tabs(uint spaces = 4)(const int num) pure nothrow @nogc
in ((num >= 0), "Negative number of tabs passed to `tabs`")
do
{
import std.range : repeat, takeExactly;
import std.algorithm.iteration : joiner;
import std.array : array;
enum char[spaces] tab = ' '.repeat.takeExactly(spaces).array;
return tab[].repeat.takeExactly(num).joiner;
}
///
@system
unittest
{
import std.array : Appender;
import std.conv : to;
import std.exception : assertThrown;
import std.format : formattedWrite;
import std.algorithm.comparison : equal;
import core.exception : AssertError;
auto one = 1.tabs!4;
auto two = 2.tabs!3;
auto three = 3.tabs!2;
auto zero = 0.tabs;
assert(one.equal(" "), one.to!string);
assert(two.equal(" "), two.to!string);
assert(three.equal(" "), three.to!string);
assert(zero.equal(string.init), zero.to!string);
assertThrown!AssertError((-1).tabs);
Appender!string sink;
sink.formattedWrite("%sHello world", 2.tabs!2);
assert((sink.data == " Hello world"), sink.data);
}
// indentInto
/++
+ Indents lines in a string into an output range sink with the supplied number of tabs.
+
+ Params:
+ spaces = How many spaces in an indenting tab.
+ wallOfText = String to indent the individual lines of.
+ sink = Output range to fill with the indented lines.
+ numTabs = Optional amount of tabs to indent with, default 1.
+/
void indentInto(uint spaces = 4, Sink)(const string wallOfText, auto ref Sink sink, const uint numTabs = 1)
if (isOutputRange!(Sink, char[]))
{
import std.algorithm.iteration : splitter;
import std.range : enumerate;
if (numTabs == 0)
{
sink.put(wallOfText);
return;
}
// Must be mutable to work with formattedWrite. That or .to!string
auto indent = numTabs.tabs!spaces;
foreach (immutable i, immutable line; wallOfText.splitter("\n").enumerate)
{
if (i > 0) sink.put("\n");
if (!line.length)
{
sink.put("\n");
continue;
}
// Cannot just put(indent), put(line) because indent is a joiner Result
import std.format : formattedWrite;
sink.formattedWrite("%s%s", indent, line);
}
}
///
unittest
{
import std.array : Appender;
Appender!(char[]) sink;
immutable string_ =
"Lorem ipsum
sit amet
I don't remember
any more offhand
so shrug";
string_.indentInto(sink);
assert((sink.data ==
" Lorem ipsum
sit amet
I don't remember
any more offhand
so shrug"), '\n' ~ sink.data);
sink.clear();
string_.indentInto!3(sink, 2);
assert((sink.data ==
" Lorem ipsum
sit amet
I don't remember
any more offhand
so shrug"), '\n' ~ sink.data);
sink.clear();
string_.indentInto(sink, 0);
assert((sink.data ==
"Lorem ipsum
sit amet
I don't remember
any more offhand
so shrug"), '\n' ~ sink.data);
}
// indent
/++
+ Indents lines in a string with the supplied number of tabs. Returns a newly
+ allocated string.
+
+ Params:
+ spaces = How many spaces make up a tab.
+ wallOfText = String to indent the lines of.
+ numTabs = Amount of tabs to indent with, default 1.
+
+ Returns:
+ A string with all the lines of the original string indented.
+/
string indent(uint spaces = 4)(const string wallOfText, const uint numTabs = 1)
{
import std.array : Appender;
Appender!string sink;
sink.reserve(wallOfText.length + 10*spaces*numTabs); // Extra room for 10 indents
wallOfText.indentInto!spaces(sink, numTabs);
return sink.data;
}
///
unittest
{
immutable string_ =
"Lorem ipsum
sit amet
I don't remember
any more offhand