-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathStrings.hx
4518 lines (3869 loc) · 156 KB
/
Strings.hx
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
/*
* SPDX-FileCopyrightText: © Vegard IT GmbH (https://vegardit.com) and contributors
* SPDX-FileContributor: Sebastian Thomschke, Vegard IT GmbH
* SPDX-License-Identifier: Apache-2.0
*/
package hx.strings;
import haxe.Int32;
#if neko
import neko.Utf8;
#else
import haxe.Utf8;
#end
import haxe.crypto.Adler32;
import haxe.crypto.Base64;
import haxe.crypto.Crc32;
import haxe.io.Bytes;
import hx.strings.Pattern.Matcher;
import hx.strings.Pattern.MatchingOption;
import hx.strings.internal.Either2;
import hx.strings.internal.Either3;
import hx.strings.internal.OS;
import hx.strings.internal.OneOrMany;
using hx.strings.Strings;
/**
* Utility functions for Strings with UTF-8 support and consistent behavior across platforms.
*
* This class can be used as <a href="http://haxe.org/manual/lf-static-extension.html">static extension</a>.
*/
class Strings {
static final REGEX_ANSI_ESC = Pattern.compile(Char.ESC + "\\[[;\\d]*m", MATCH_ALL);
static final REGEX_HTML_UNESCAPE = Pattern.compile("&(#\\d+|amp|nbsp|apos|lt|gt|quot);", MATCH_ALL);
static final REGEX_SPLIT_LINES = Pattern.compile("\\r?\\n", MATCH_ALL);
#if !php
static final REGEX_REMOVE_XML_TAGS = Pattern.compile("<[!a-zA-Z\\/][^>]*>", MATCH_ALL);
#end
public static inline final POS_NOT_FOUND:CharIndex = -1;
/**
* Unix line separator (LF)
*/
public static inline final NEW_LINE_NIX = "\n";
/**
* Windows line separator (CR + LF)
*/
public static inline final NEW_LINE_WIN = "\r\n";
/**
* operating system specific line separator
*/
public static final NEW_LINE = OS.isWindows ? NEW_LINE_WIN : NEW_LINE_NIX;
/*
* workaround for https://github.com/HaxeFoundation/haxe/issues/10343
*/
inline
private static function _length(str:String):Int {
#if lua
return cast(str, String).length;
#else
return str.length;
#end
}
inline
private static function _getNotFoundDefault(str:Null<String>, notFoundDefault:StringNotFoundDefault):Null<String> {
return switch(notFoundDefault) {
case NULL: null;
case EMPTY: "";
case INPUT: str;
}
}
/**
* no null / bounds checking
*/
// to prevent "lua53: target/lua/TestRunner.lua:24443: ')' expected near ':'"
@:allow(hx.strings.CharIterator)
#if !lua inline #end
private static function _charCodeAt8Unsafe(str:Null<String>, pos:CharIndex):Char {
@:nullSafety(Off)
#if target.unicode
return cast str.charCodeAt(pos);
#else
return Utf8.charCodeAt(str, pos);
#end
}
/**
* no bounds checking
*/
private static function _splitAsciiWordsUnsafe(str:String) {
final words = new Array<String>();
final currentWord = new StringBuilder();
final chars = str.toChars();
final len = chars.length;
final lastIndex = len - 1;
for (i in 0...len) {
final ch = chars[i];
if (ch.isAsciiAlpha()) {
final chNext = i < lastIndex ? chars[i + 1] : -1;
currentWord.addChar(ch);
if (chNext.isDigit()) {
words.push(currentWord.toString());
currentWord.clear();
} else if (ch.isUpperCase()) {
if (chNext.isUpperCase() && chars.length > i + 2) {
if (!chars[i + 2].isUpperCase()) {
words.push(currentWord.toString());
currentWord.clear();
}
}
} else { /*if (!ch.isUpperCase()) */
if (chNext.isUpperCase()) {
words.push(currentWord.toString());
currentWord.clear();
}
}
} else if (ch.isDigit()) {
currentWord.addChar(ch);
final chNext = i < lastIndex ? chars[i + 1] : -1;
if (!chNext.isDigit()) {
words.push(currentWord.toString());
currentWord.clear();
}
} else if (currentWord.length > 0) {
words.push(currentWord.toString());
currentWord.clear();
}
}
if (currentWord.length > 0)
words.push(currentWord.toString());
return words;
}
/**
* Transforms an ANSI escape sequence to HTML markup.
*
* There are currently three different render methods available:
*
* 1. <b>StyleAttributes (the default):</b> transforms to linear style attribute such as <pre><span style=\"color:yellow\;">content</span></pre>.
*
* 2. <b>CssClasses:</b> Uses <b>AnsiState#defaultCssClassesCallback()</b> which converts to CSS classes named such as
* <span class="ansi_fg_red ansi_bold"></span>, where "red" is the ANSI color.
* The CSS classes used by default are .ansi_fg_<color>, .ansi_bg_<color>, .ansi_bold, .ansi_blink, .ansi_underline.
*
* 3. <b>CssClassesCallback(cb):</b> allows full customization via a custom callback AnsiState->String.
* The returned string is the CSS class name applied for the given AnsiState.
*
* <pre><code>
* >>> Strings.ansiToHtml(null) == null
* >>> Strings.ansiToHtml("") == ""
* >>> Strings.ansiToHtml("dogcat") == "dogcat"
* >>> Strings.ansiToHtml("\x1B[0m\x1B[0m") == ""
* >>> Strings.ansiToHtml("\x1B[33;40mDOG\x1B[40;42mCAT") == "<span style=\"color:yellow;background-color:black;\">DOG</span><span style=\"color:yellow;background-color:green;\">CAT</span>"
* >>> Strings.ansiToHtml("\x1B[33;40mDOG\x1B[40;42mCAT\x1B[0m") == "<span style=\"color:yellow;background-color:black;\">DOG</span><span style=\"color:yellow;background-color:green;\">CAT</span>"
* >>> Strings.ansiToHtml("\x1B[33;40mDOG\x1B[40;42mCAT\x1B[0m", CssClasses) == "<span class=\"ansi_fg_yellow ansi_bg_black\">DOG</span><span class=\"ansi_fg_yellow ansi_bg_green\">CAT</span>"
* </code></pre>
*/
public static function ansiToHtml<T:String>(str:T, ?renderMethod:AnsiToHtmlRenderMethod, ?initialState:AnsiState):T {
if (isEmpty(str))
return str;
#if php final str:String = str; #end
if (renderMethod == null) renderMethod = StyleAttributes;
final styleOrClassAttribute = switch(renderMethod) {
case StyleAttributes : "style";
case CssClasses : "class";
case CssClassesCallback(cb) : "class";
}
final sb = new StringBuilder();
if (initialState != null && initialState.isActive())
sb.add('<span $styleOrClassAttribute=\"').add(initialState.toCSS(renderMethod)).add("\">");
var effectiveState = new AnsiState(initialState);
final strLenMinus1 = str.length8() - 1;
var i = -1;
final lookAhead = new StringBuilder();
while (i < strLenMinus1) {
i++;
final ch:Char = str._charCodeAt8Unsafe(i);
if (ch == Char.ESC && i < strLenMinus1 && str._charCodeAt8Unsafe(i + 1) == 91 /*[*/) { // is beginning of ANSI Escape Sequence?
lookAhead.clear();
final currentState = new AnsiState(effectiveState);
var currentGraphicModeParam = 0;
var isValidEscapeSequence = false;
i += 1;
while (i < strLenMinus1) {
i++;
final ch2:Char = str._charCodeAt8Unsafe(i);
lookAhead.addChar(ch2);
switch (ch2) {
case 48: currentGraphicModeParam = currentGraphicModeParam * 10 + 0;
case 49: currentGraphicModeParam = currentGraphicModeParam * 10 + 1;
case 50: currentGraphicModeParam = currentGraphicModeParam * 10 + 2;
case 51: currentGraphicModeParam = currentGraphicModeParam * 10 + 3;
case 52: currentGraphicModeParam = currentGraphicModeParam * 10 + 4;
case 53: currentGraphicModeParam = currentGraphicModeParam * 10 + 5;
case 54: currentGraphicModeParam = currentGraphicModeParam * 10 + 6;
case 55: currentGraphicModeParam = currentGraphicModeParam * 10 + 7;
case 56: currentGraphicModeParam = currentGraphicModeParam * 10 + 8;
case 57: currentGraphicModeParam = currentGraphicModeParam * 10 + 9;
case Char.SEMICOLON: // graphic mode separator
currentState.setGraphicModeParameter(currentGraphicModeParam);
currentGraphicModeParam = 0;
case 109: // escape sequence terminator 'm'
currentState.setGraphicModeParameter(currentGraphicModeParam);
if (effectiveState.isActive())
sb.add("</span>");
if (currentState.isActive())
sb.add('<span $styleOrClassAttribute=\"').add(currentState.toCSS(renderMethod)).add("\">");
effectiveState = currentState;
isValidEscapeSequence = true;
break; // break out of the while loop
default:
// invalid character found
break; // break out of the while loop
}
}
if (!isValidEscapeSequence) {
// in case of a missing ESC sequence delimiter, we treat the whole ESC string not as an ANSI escape sequence
sb.addChar(Char.ESC).add('[').add(lookAhead);
}
} else
sb.addChar(ch);
}
if (effectiveState.isActive())
sb.add("</span>");
return cast sb.toString();
}
/**
* <pre><code>
* >>> Strings.appendIfMissing(null, null) == null
* >>> Strings.appendIfMissing(null, "") == null
* >>> Strings.appendIfMissing("", "") == ""
* >>> Strings.appendIfMissing("", " ") == " "
* >>> Strings.appendIfMissing("dog", null) == "dognull"
* >>> Strings.appendIfMissing("dog", "/") == "dog/"
* >>> Strings.appendIfMissing("dog/", "/") == "dog/"
* >>> Strings.appendIfMissing("はい", "はい") == "はい"
* >>> Strings.appendIfMissing("はい", "は") == "はいは"
* </code></pre>
*/
public static function appendIfMissing<T:String>(str:T, suffix:T):T {
if (str == null)
return cast null;
if (str._length() == 0)
return cast str + suffix;
if (str.endsWith(suffix))
return cast str;
return cast str + suffix;
}
/**
* <pre><code>
* >>> Strings.base64Encode(null) == null
* >>> Strings.base64Encode("") == ""
* >>> Strings.base64Encode("dog") == "ZG9n"
* >>> Strings.base64Encode("はい") == "44Gv44GE"
* </code></pre>
*/
inline
public static function base64Encode<T:String>(plain:T):T {
if (plain == null)
return cast null;
#if php
return cast php.Syntax.code("base64_encode({0})", plain);
#else
@:nullSafety(Off)
return cast Base64.encode(plain.toBytes());
#end
}
/**
* <pre><code>
* >>> Strings.base64Decode(null) == null
* >>> Strings.base64Decode("") == ""
* >>> Strings.base64Decode("ZG9n") == "dog"
* >>> Strings.base64Decode("44Gv44GE") == "はい"
* </code></pre>
*/
inline
public static function base64Decode<T:String>(encoded:T):T {
if (encoded == null)
return cast null;
#if php
return cast php.Syntax.code("base64_decode({0})", encoded);
#else
return cast Base64.decode(encoded).toString();
#end
}
/**
* String#charAt() variant with cross-platform UTF-8 support.
*
* <pre><code>
* >>> Strings.charAt8(" dog", 0) == " "
* >>> Strings.charAt8(" dog", 1 ) == "d"
* >>> Strings.charAt8(" ", -1) == ""
* >>> Strings.charAt8(" ", -1, "x") == "x"
* >>> Strings.charAt8(" ", 0) == " "
* >>> Strings.charAt8(" ", 1) == ""
* >>> Strings.charAt8(" ", 10) == ""
* >>> Strings.charAt8("", 0) == ""
* >>> Strings.charAt8("", 0, "x") == "x"
* >>> Strings.charAt8(null, 0) == ""
* >>> Strings.charAt8(" はい", 1) == "は"
* >>> Strings.charAt8(" はい", 2) == "い"
* </code></pre>
*
* @param pos character position
*/
public static function charAt8<T:String>(str:T, pos:CharIndex, resultIfOutOfBound = ""):T {
if (str.isEmpty() || pos < 0 || pos >= str.length8())
return cast resultIfOutOfBound;
#if target.unicode
return cast str.charAt(pos);
#else
return cast Utf8.sub(str, pos, 1);
#end
}
/**
* String#charCodeAt() variant with cross-platform UTF-8 support.
*
* <pre><code>
* >>> Strings.charCodeAt8(" dog", 0) == 32
* >>> Strings.charCodeAt8(" dog", 0).isSpace() == true
* >>> Strings.charCodeAt8(" dog", 1) == 100
* >>> Strings.charCodeAt8(" dog", 1).isSpace() == false
* >>> Strings.charCodeAt8(" ", -1) == -1
* >>> Strings.charCodeAt8(" ", -1, -4) == -4
* >>> Strings.charCodeAt8(" ", 0) == 32
* >>> Strings.charCodeAt8(" ", 0).isSpace() == true
* >>> Strings.charCodeAt8(" ", 1) == -1
* >>> Strings.charCodeAt8(" ", 1).isSpace() == false
* >>> Strings.charCodeAt8(" ", 10) == -1
* >>> Strings.charCodeAt8("", 0) == -1
* >>> Strings.charCodeAt8("", 0, -4) == -4
* >>> Strings.charCodeAt8(null, 0) == -1
* >>> Strings.charCodeAt8(null, 0).isSpace() == false
* >>> Strings.charCodeAt8(" はい", 1) == 12399
* >>> Strings.charCodeAt8(" はい", 2) == 12356
* </code></pre>
*
* @param pos character position
*/
public static function charCodeAt8(str:Null<String>, pos:CharIndex, resultIfOutOfBound:Char = -1):Char {
final strLen = str.length8();
if (strLen == 0 || pos < 0 || pos >= strLen)
return resultIfOutOfBound;
return str._charCodeAt8Unsafe(pos);
}
/**
* Removes trailing and leading whitespace characters.
* Replaces all whitespace characters with the space character.
* Only leaves one space character between words.
*
* <pre><code>
* >>> Strings.compact(null) == null
* >>> Strings.compact("") == ""
* >>> Strings.compact(" dog \n \t cat ") == "dog cat"
* </code></pre>
*/
public static function compact<T:String>(str:T):T {
if (str.isEmpty())
return str;
final sb = new StringBuilder();
var needWhiteSpace = false;
for (char in str.toChars()) {
if (char.isWhitespace()) {
if (!sb.isEmpty())
needWhiteSpace = true;
continue;
} else if (needWhiteSpace) {
sb.addChar(Char.SPACE);
needWhiteSpace = false;
}
sb.addChar(char);
}
return cast sb.toString();
}
/**
* Tests if <b>searchIn</b> contains <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.contains("dog", "") == true
* >>> Strings.contains("dog", "g") == true
* >>> Strings.contains("dog", "t") == false
* >>> Strings.contains("", null) == false
* >>> Strings.contains("", "") == true
* >>> Strings.contains(null, null) == false
* >>> Strings.contains(null, "") == false
* >>> Strings.contains("はい", "い") == true
* >>> Strings.contains("はは", "い") == false
* </code></pre>
*/
inline
public static function contains(searchIn:Null<String>, searchFor:Null<String>):Bool {
if (searchIn == null || searchFor == null)
return false;
if (searchFor == "")
return true;
return searchIn.indexOf(searchFor) > POS_NOT_FOUND;
}
/**
* Tests if <b>searchIn</b> contains only the allowed characters
*
* <pre><code>
* >>> Strings.containsOnly(null, null) == true
* >>> Strings.containsOnly("", null) == true
* >>> Strings.containsOnly("a", null) == false
* >>> Strings.containsOnly("AA", [65]) == true
* >>> Strings.containsOnly("Aa", [65]) == false
* >>> Strings.containsOnly("AA", "A") == true
* >>> Strings.containsOnly("Aa", "A") == false
* >>> Strings.containsOnly("Aa", "Aa") == true
* </code></pre>
*/
public static function containsOnly(searchIn:Null<String>, allowedChars:Null<Either2<String, Array<Char>>>):Bool {
if (searchIn.isEmpty())
return true;
if (allowedChars == null)
return false;
final allowedCharsArray:Array<Char> = switch (allowedChars.value) {
case a(str): str.toChars();
case b(chars): chars;
}
for (ch in searchIn.toChars()) {
if (allowedCharsArray.indexOf(ch) < 0)
return false;
}
return true;
}
/**
* Tests if <b>searchIn</b> contains all of <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.containsAll("dog", ["c", ""]) == false
* >>> Strings.containsAll("dog", ["c", "g"]) == false
* >>> Strings.containsAll("dog", ["c", "a"]) == false
* >>> Strings.containsAll("dog", ["d", "g"]) == true
* >>> Strings.containsAll("dog", [""]) == true
* >>> Strings.containsAll("", null) == false
* >>> Strings.containsAll("", [""]) == true
* >>> Strings.containsAll(null, null) == false
* >>> Strings.containsAll(null, [""]) == false
* >>> Strings.containsAll("はい", ["い"]) == true
* >>> Strings.containsAll("はは", ["い"]) == false
* </code></pre>
*/
public static function containsAll(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool {
if (searchIn == null || searchFor == null)
return false;
for (candidate in searchFor) {
if (!contains(searchIn, candidate))
return false;
}
return true;
}
/**
* Tests if <b>searchIn</b> contains all of <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.containsAllIgnoreCase("dog", ["c", ""]) == false
* >>> Strings.containsAllIgnoreCase("dog", ["c", "G"]) == false
* >>> Strings.containsAllIgnoreCase("dog", ["c", "a"]) == false
* >>> Strings.containsAllIgnoreCase("dog", ["d", "G"]) == true
* >>> Strings.containsAllIgnoreCase("dog", [""]) == true
* >>> Strings.containsAllIgnoreCase("", null) == false
* >>> Strings.containsAllIgnoreCase("", [""]) == true
* >>> Strings.containsAllIgnoreCase(null, null) == false
* >>> Strings.containsAllIgnoreCase(null, [""]) == false
* >>> Strings.containsAllIgnoreCase("はい", ["い"]) == true
* >>> Strings.containsAllIgnoreCase("はは", ["い"]) == false
* </code></pre>
*/
public static function containsAllIgnoreCase(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool {
if (searchIn == null || searchFor == null)
return false;
searchIn = searchIn.toLowerCase();
for (candidate in searchFor) {
if (!contains(searchIn, candidate.toLowerCase()))
return false;
}
return true;
}
/**
* Tests if <b>searchIn</b> contains any of <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.containsAny("dog", ["c", ""]) == true
* >>> Strings.containsAny("dog", ["c", "g"]) == true
* >>> Strings.containsAny("dog", ["", "g"]) == true
* >>> Strings.containsAny("dog", ["c", "a"]) == false
* >>> Strings.containsAny("dog", ["d", "g"]) == true
* >>> Strings.containsAny("dog", [""]) == true
* >>> Strings.containsAny("", null) == false
* >>> Strings.containsAny("", [""]) == true
* >>> Strings.containsAny(null, null) == false
* >>> Strings.containsAny(null, [""]) == false
* >>> Strings.containsAny("はい", ["い"]) == true
* >>> Strings.containsAny("はは", ["い"]) == false
* </code></pre>
*/
public static function containsAny(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool {
if (searchIn == null || searchFor == null)
return false;
for (candidate in searchFor) {
if (contains(searchIn, candidate))
return true;
}
return false;
}
/**
* Tests if <b>searchIn</b> contains any of <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.containsAnyIgnoreCase("dog", ["c", ""]) == true
* >>> Strings.containsAnyIgnoreCase("dog", ["c", "G"]) == true
* >>> Strings.containsAnyIgnoreCase("dog", ["c", "a"]) == false
* >>> Strings.containsAnyIgnoreCase("dog", ["d", "G"]) == true
* >>> Strings.containsAnyIgnoreCase("dog", [""]) == true
* >>> Strings.containsAnyIgnoreCase("", null) == false
* >>> Strings.containsAnyIgnoreCase("", [""]) == true
* >>> Strings.containsAnyIgnoreCase(null, null) == false
* >>> Strings.containsAnyIgnoreCase(null, [""]) == false
* >>> Strings.containsAnyIgnoreCase("はい", ["い"]) == true
* >>> Strings.containsAnyIgnoreCase("はは", ["い"]) == false
* </code></pre>
*/
public static function containsAnyIgnoreCase(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool {
if (searchIn == null || searchFor == null)
return false;
searchIn = searchIn.toLowerCase();
for (candidate in searchFor) {
if (contains(searchIn, candidate.toLowerCase()))
return true;
}
return false;
}
/**
* Checks that <b>searchIn</b> contains none of <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.containsNone("dog", ["c", ""]) == false
* >>> Strings.containsNone("dog", ["c", "g"]) == false
* >>> Strings.containsNone("dog", ["c", "a"]) == true
* >>> Strings.containsNone("dog", ["d", "g"]) == false
* >>> Strings.containsNone("dog", [""]) == false
* >>> Strings.containsNone("", null) == true
* >>> Strings.containsNone("", [""]) == false
* >>> Strings.containsNone(null, null) == true
* >>> Strings.containsNone(null, [""]) == true
* >>> Strings.containsNone("はい", ["い"]) == false
* >>> Strings.containsNone("はは", ["い"]) == true
* </code></pre>
*/
inline
public static function containsNone(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool
return !containsAny(searchIn, searchFor);
/**
* Checks that <b>searchIn</b> contains none of <b>searchFor</b> as a substring
*
* <pre><code>
* >>> Strings.containsNoneIgnoreCase("dog", ["c", ""]) == false
* >>> Strings.containsNoneIgnoreCase("dog", ["c", "G"]) == false
* >>> Strings.containsNoneIgnoreCase("dog", ["c", "a"]) == true
* >>> Strings.containsNoneIgnoreCase("dog", ["d", "G"]) == false
* >>> Strings.containsNoneIgnoreCase("dog", [""]) == false
* >>> Strings.containsNoneIgnoreCase("", null) == true
* >>> Strings.containsNoneIgnoreCase("", [""]) == false
* >>> Strings.containsNoneIgnoreCase(null, null) == true
* >>> Strings.containsNoneIgnoreCase(null, [""]) == true
* >>> Strings.containsNoneIgnoreCase("はい", ["い"]) == false
* >>> Strings.containsNoneIgnoreCase("はは", ["い"]) == true
* </code></pre>
*/
inline
public static function containsNoneIgnoreCase(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool
return !containsAnyIgnoreCase(searchIn, searchFor);
/**
* Tests if <b>searchIn</b> contains any whitespaces
*
* <pre><code>
* >>> Strings.containsWhitespaces(" ") == true
* >>> Strings.containsWhitespaces("dog cat") == true
* >>> Strings.containsWhitespaces("dog\tcat") == true
* >>> Strings.containsWhitespaces("") == false
* >>> Strings.containsWhitespaces(null) == false
* >>> Strings.containsWhitespaces("はい") == false
* >>> Strings.containsWhitespaces("は い") == true
* </code></pre>
*/
public static function containsWhitespaces(searchIn:Null<String>):Bool {
if (searchIn == null)
return false;
for (ch in searchIn.toChars()) {
if (ch.isWhitespace())
return true;
}
return false;
}
/**
* <pre><code>
* >>> Strings.countMatches("dogdog", "g") == 2
* >>> Strings.countMatches("dogdog", "og", 1) == 2
* >>> Strings.countMatches("dogdog", "og", 3) == 1
* >>> Strings.countMatches("dogdog", "og", 9) == 0
* >>> Strings.countMatches("dogdog", "og", -1) == 2
* >>> Strings.countMatches("", null) == 0
* >>> Strings.countMatches("", "a") == 0
* >>> Strings.countMatches(null, null) == 0
* >>> Strings.countMatches(null, "") == 0
* </code></pre>
*
* @return the number of occurrences of <b>searchFor</b> within <b>searchIn</b> starting
* from the given character position.
*/
public static function countMatches(searchIn:Null<String>, searchFor:Null<String>, startAt:CharIndex = 0):Int {
if (searchIn.isEmpty() || searchFor.isEmpty() || startAt >= searchIn.length)
return 0;
if (startAt < 0)
startAt = 0;
var count = 0;
var foundAt = startAt > -1 ? startAt - 1 : 0;
while ((foundAt = searchIn.indexOf(searchFor, foundAt + 1)) > -1)
count++;
return count;
}
/**
* <pre><code>
* >>> Strings.countMatchesIgnoreCase("dogdog", "G") == 2
* >>> Strings.countMatchesIgnoreCase("dogdog", "OG", 1) == 2
* >>> Strings.countMatchesIgnoreCase("dogdog", "OG", 3) == 1
* >>> Strings.countMatchesIgnoreCase("dogdog", "OG", 9) == 0
* >>> Strings.countMatchesIgnoreCase("dogdog", "OG", -1) == 2
* >>> Strings.countMatchesIgnoreCase(null, null) == 0
* >>> Strings.countMatchesIgnoreCase(null, "") == 0
* >>> Strings.countMatchesIgnoreCase("", null) == 0
* >>> Strings.countMatchesIgnoreCase("", "a") == 0
* </code></pre>
*
* @return the number of occurrences of <b>searchFor</b> within <b>searchIn</b> starting
* from the given character position ignoring case.
*/
public static function countMatchesIgnoreCase(searchIn:Null<String>, searchFor:Null<String>, startAt:CharIndex = 0):Int {
if (searchIn.isEmpty() || searchFor.isEmpty() || startAt >= searchIn.length)
return 0;
if (startAt < 0)
startAt = 0;
searchIn = searchIn.toLowerCase();
searchFor = searchFor.toLowerCase();
var count = 0;
var foundAt = startAt > -1 ? startAt - 1 : 0;
while ((foundAt = searchIn.indexOf(searchFor, foundAt + 1)) > -1)
count++;
return count;
}
/**
* <pre><code>
* >>> Strings.compare("a", "b") < 0
* >>> Strings.compare("b", "a") > 0
* >>> Strings.compare("a", "A") > 0
* >>> Strings.compare("A", "a") < 0
* >>> Strings.compare("a", "B") > 0
* >>> Strings.compare("", null) > 0
* >>> Strings.compare("", "") == 0
* >>> Strings.compare(null, null) == 0
* >>> Strings.compare(null, "") < 0
* >>> Strings.compare("к--", "К--") > 0
* >>> Strings.compare("к--", "т--") < 0
* >>> Strings.compare("кот", "КОТ") > 0
* </core></pre>
*
* @return a positive value if `str > other`, negative value if `str < other`, 0 if `str == other`
*/
public static function compare(str:Null<String>, other:Null<String>):Int {
if (str == null)
return other == null ? 0 : -1;
if (other == null)
return str == null ? 0 : 1;
#if target.unicode
return str > other ? 1 : (str == other ? 0 : -1);
#else
return Utf8.compare(str, other);
#end
}
/**
* <pre><code>
* >>> Strings.compareIgnoreCase("a", "b") < 0
* >>> Strings.compareIgnoreCase("b", "a") > 0
* >>> Strings.compareIgnoreCase("a", "A") == 0
* >>> Strings.compareIgnoreCase("A", "a") == 0
* >>> Strings.compareIgnoreCase("a", "B") < 0
* >>> Strings.compareIgnoreCase("", null) > 0
* >>> Strings.compareIgnoreCase("", "") == 0
* >>> Strings.compareIgnoreCase(null, null) == 0
* >>> Strings.compareIgnoreCase(null, "") < 0
* >>> Strings.compareIgnoreCase("к--", "К--") == 0
* >>> Strings.compareIgnoreCase("к--", "т--") < 0
* >>> Strings.compareIgnoreCase("кот", "КОТ") == 0
* </core></pre>
*
* @return a positive value if `str > other`, negative value if `str < other`, 0 if `str == other`
*/
public static function compareIgnoreCase(str:Null<String>, other:Null<String>):Int {
if (str == null)
return other == null ? 0 : -1;
if (other == null)
return str == null ? 0 : 1;
@:nullSafety(Off) final str:String = str.toLowerCase8();
@:nullSafety(Off) final other:String = other.toLowerCase8();
#if target.unicode
return str > other ? 1 : (str == other ? 0 : -1);
#else
return @:nullSafety(Off) Utf8.compare(str, other);
#end
}
/**
* <pre><code>
* >>> Strings.diff("abc", "abC").left == "c"
* >>> Strings.diff("abc", "abC").right == "C"
* >>> Strings.diff("ab", "abC").left == ""
* >>> Strings.diff("ab", "abC").right == "C"
* >>> Strings.diff(null, null).at == -1
* >>> Strings.diff(null, "").at == 0
* >>> Strings.diff(null, "").left == null
* >>> Strings.diff(null, "").right == ""
* </code></pre>
*/
public static function diff(left:Null<String>, right:Null<String>):StringDiff {
final diff = new StringDiff();
diff.at = diffAt(left, right);
diff.left = left.substr8(diff.at);
diff.right = right.substr8(diff.at);
return diff;
}
/**
* <pre><code>
* >>> Strings.diffAt("cat", "catdog") == 3
* >>> Strings.diffAt("cat", "cat") == -1
* >>> Strings.diffAt("cat", "") == 0
* >>> Strings.diffAt("cat", "dog") == 0
* >>> Strings.diffAt("It's green", "It's red") == 5
* >>> Strings.diffAt("catdog", "cat") == 3
* >>> Strings.diffAt(null, null) == -1
* >>> Strings.diffAt(null, "") == 0
* >>> Strings.diffAt("", null) == 0
* >>> Strings.diffAt("", "") == -1
* >>> Strings.diffAt("", "cat") == 0
* </code></pre>
*
* @return the UTF8 character position where the strings begin to differ or -1 if they are equal
*/
public static function diffAt(str:Null<String>, other:Null<String>):CharIndex {
if (str.equals(other))
return POS_NOT_FOUND;
final strLen = str.length8();
final otherLen = other.length8();
if (strLen == 0 || otherLen == 0)
return 0;
final checkLen = strLen > otherLen ? otherLen : strLen;
for (i in 0...checkLen)
if (str._charCodeAt8Unsafe(i) != other._charCodeAt8Unsafe(i))
return i;
return checkLen;
}
/**
* <pre><code>
* >>> Strings.ellipsizeLeft("12345678", 5) == "...78"
* >>> Strings.ellipsizeLeft("12345", 4) == "...5"
* >>> Strings.ellipsizeLeft("1234", 4) == "1234"
* >>> Strings.ellipsizeLeft("", 0) == ""
* >>> Strings.ellipsizeLeft("", 3) == ""
* >>> Strings.ellipsizeLeft(null, 0) == null
* >>> Strings.ellipsizeLeft(null, 3) == null
* >>> Strings.ellipsizeLeft("はいはいはい", 5) == "...はい"
* </code></pre>
*
* @throws exception if maxLength < ellipsis.length
*/
public static function ellipsizeLeft<T:String>(str:T, maxLength:Int, ellipsis:String = "..."):T {
if (str.length8() <= maxLength)
return str;
final ellipsisLen = ellipsis.length8();
if (maxLength < ellipsisLen) throw '[maxLength] must not be smaller than ${ellipsisLen}';
return cast ellipsis + str.right(maxLength - ellipsisLen);
}
/**
* <pre><code>
* >>> Strings.ellipsizeMiddle("12345678", 5) == "1...8"
* >>> Strings.ellipsizeMiddle("12345", 4) == "1..."
* >>> Strings.ellipsizeMiddle("1234", 4) == "1234"
* >>> Strings.ellipsizeMiddle("", 0) == ""
* >>> Strings.ellipsizeMiddle("", 3) == ""
* >>> Strings.ellipsizeMiddle(null, 0) == null
* >>> Strings.ellipsizeMiddle(null, 3) == null
* >>> Strings.ellipsizeMiddle("はいはいはい", 5) == "は...い"
* </code></pre>
*
* @throws exception if maxLength < ellipsis.length
*/
public static function ellipsizeMiddle<T:String>(str:T, maxLength:Int, ellipsis:String = "..."):T {
final strLen = str.length8();
if (strLen <= maxLength)
return str;
final ellipsisLen = ellipsis.length8();
if (maxLength < ellipsisLen) throw '[maxLength] must not be smaller than ${ellipsisLen}';
final maxStrLen = maxLength - ellipsisLen;
final leftLen = Math.round(maxStrLen / 2);
final rightLen = maxStrLen - leftLen;
return cast str.left(leftLen) + ellipsis + str.right(rightLen);
}
/**
* <pre><code>
* >>> Strings.ellipsizeRight("12345678", 5) == "12..."
* >>> Strings.ellipsizeRight("12345", 4) == "1..."
* >>> Strings.ellipsizeRight("1234", 4) == "1234"
* >>> Strings.ellipsizeRight("", 0) == ""
* >>> Strings.ellipsizeRight("", 3) == ""
* >>> Strings.ellipsizeRight(null, 0) == null
* >>> Strings.ellipsizeRight(null, 3) == null
* >>> Strings.ellipsizeRight("はいはいはい", 5) == "はい..."
* </code></pre>
*
* @throws exception if maxLength < ellipsis.length
*/
public static function ellipsizeRight<T:String>(str:T, maxLength:Int, ellipsis:String = "..."):T {
if (str.length8() <= maxLength)
return str;
final ellipsisLen = ellipsis.length8();
if (maxLength < ellipsisLen) throw '[maxLength] must not be smaller than ${ellipsisLen}';
return cast str.left(maxLength - ellipsisLen) + ellipsis;
}
/**
* <pre><code>
* >>> Strings.endsWith("dogcat", "cat") == true
* >>> Strings.endsWith("dogcat", "dog") == false
* >>> Strings.endsWith("dogcat", "") == true
* >>> Strings.endsWith("dogcat", null) == false
* >>> Strings.endsWith("", "") == true
* >>> Strings.endsWith(null, "cat") == false
* >>> Strings.endsWith("aňa", "ňa") == true
* >>> Strings.endsWith("はい", "い") == true
* >>> Strings.endsWith("はい", "は") == false
* >>> Strings.endsWith("\u{1F604}\u{1F619}", "\u{1F604}\u{1F619}") == true
* </code></pre>
*/
public static function endsWith(searchIn:Null<String>, searchFor:Null<String>):Bool {
if (searchIn == null || searchFor == null)
return false;
#if lua
// dramatically faster than StringTools.endsWith
return searchFor == "" || untyped __lua__("{0}:sub(-#{1}) == {1}", searchIn, searchFor);
#elseif cpp
// TODO StringTools.endsWith doesn't work with UTF8 chars on Haxe4+CPP
final searchInLen = searchIn.length;
final searchForLen = searchFor.length;
return searchInLen >= searchForLen && searchIn.indexOf(searchFor, searchInLen - searchForLen) > POS_NOT_FOUND;
#else
return StringTools.endsWith(searchIn, searchFor);
#end
}
/**
* <pre><code>
* >>> Strings.endsWithAny(null, ["cat"]) == false
* >>> Strings.endsWithAny("", [""]) == true
* >>> Strings.endsWithAny("dogcat", null) == false
* >>> Strings.endsWithAny("dogcat", [null]) == false
* >>> Strings.endsWithAny("dogcat", [""]) == true
* >>> Strings.endsWithAny("dogcat", ["cat"]) == true
* >>> Strings.endsWithAny("dogcat", ["dog", "cat"]) == true
* >>> Strings.endsWithAny("dogcat", ["dog"]) == false
* >>> Strings.endsWithAny("はい", ["は", "い"]) == true
* >>> Strings.endsWithAny("はい", ["は"]) == false
* </code></pre>
*/
public static function endsWithAny(searchIn:Null<String>, searchFor:Null<Array<String>>):Bool {
if (searchIn == null || searchFor == null)
return false;
for (candidate in searchFor)
if (candidate != null && endsWith(searchIn, candidate))
return true;
return false;
}
/**
* <pre><code>