forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringExtensions.cs
More file actions
1250 lines (1051 loc) · 41 KB
/
StringExtensions.cs
File metadata and controls
1250 lines (1051 loc) · 41 KB
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
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ServiceStack.Text;
using ServiceStack.Text.Common;
using ServiceStack.Text.Support;
using static System.String;
namespace ServiceStack
{
public static class StringExtensions
{
public static T To<T>(this string value)
{
return TypeSerializer.DeserializeFromString<T>(value);
}
public static T To<T>(this string value, T defaultValue)
{
return String.IsNullOrEmpty(value) ? defaultValue : TypeSerializer.DeserializeFromString<T>(value);
}
public static T ToOrDefaultValue<T>(this string value)
{
return String.IsNullOrEmpty(value) ? default(T) : TypeSerializer.DeserializeFromString<T>(value);
}
public static object To(this string value, Type type)
{
return TypeSerializer.DeserializeFromString(value, type);
}
/// <summary>
/// Converts from base: 0 - 62
/// </summary>
/// <param name="source">The source.</param>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <returns></returns>
public static string BaseConvert(this string source, int from, int to)
{
var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var len = source.Length;
if (len == 0)
throw new Exception(Format("Parameter: '{0}' is not valid integer (in base {1}).", source, from));
var minus = source[0] == '-' ? "-" : "";
var src = minus == "" ? source : source.Substring(1);
len = src.Length;
if (len == 0)
throw new Exception(Format("Parameter: '{0}' is not valid integer (in base {1}).", source, from));
var d = 0;
for (int i = 0; i < len; i++) // Convert to decimal
{
int c = chars.IndexOf(src[i]);
if (c >= from)
throw new Exception(Format("Parameter: '{0}' is not valid integer (in base {1}).", source, from));
d = d * from + c;
}
if (to == 10 || d == 0)
return minus + d;
var result = "";
while (d > 0) // Convert to desired
{
result = chars[d % to] + result;
d /= to;
}
return minus + result;
}
public static string EncodeXml(this string value)
{
return value.Replace("<", "<").Replace(">", ">").Replace("&", "&");
}
public static string EncodeJson(this string value)
{
return Concat
("\"",
value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "\\n"),
"\""
);
}
public static string EncodeJsv(this string value)
{
if (JsState.QueryStringMode)
{
return UrlEncode(value);
}
return String.IsNullOrEmpty(value) || !JsWriter.HasAnyEscapeChars(value)
? value
: Concat
(
JsWriter.QuoteString,
value.Replace(JsWriter.QuoteString, TypeSerializer.DoubleQuoteString),
JsWriter.QuoteString
);
}
public static string DecodeJsv(this string value)
{
const int startingQuotePos = 1;
const int endingQuotePos = 2;
return String.IsNullOrEmpty(value) || value[0] != JsWriter.QuoteChar
? value
: value.Substring(startingQuotePos, value.Length - endingQuotePos)
.Replace(TypeSerializer.DoubleQuoteString, JsWriter.QuoteString);
}
public static string UrlEncode(this string text, bool upperCase=false)
{
if (String.IsNullOrEmpty(text)) return text;
var sb = StringBuilderThreadStatic.Allocate();
var fmt = upperCase ? "X2" : "x2";
foreach (var charCode in Encoding.UTF8.GetBytes(text))
{
if (
charCode >= 65 && charCode <= 90 // A-Z
|| charCode >= 97 && charCode <= 122 // a-z
|| charCode >= 48 && charCode <= 57 // 0-9
|| charCode >= 44 && charCode <= 46 // ,-.
)
{
sb.Append((char)charCode);
}
else if(charCode == 32)
{
sb.Append('+');
}
else
{
sb.Append('%' + charCode.ToString(fmt));
}
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
public static string UrlDecode(this string text)
{
if (String.IsNullOrEmpty(text)) return null;
var bytes = new List<byte>();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text[i];
if (c == '+')
{
bytes.Add(32);
}
else if (c == '%')
{
var hexNo = Convert.ToByte(text.Substring(i + 1, 2), 16);
bytes.Add(hexNo);
i += 2;
}
else
{
bytes.Add((byte)c);
}
}
byte[] byteArray = bytes.ToArray();
return Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
public static string HexUnescape(this string text, params char[] anyCharOf)
{
if (String.IsNullOrEmpty(text)) return null;
if (anyCharOf == null || anyCharOf.Length == 0) return text;
var sb = StringBuilderThreadStatic.Allocate();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text.Substring(i, 1);
if (c == "%")
{
var hexNo = Convert.ToInt32(text.Substring(i + 1, 2), 16);
sb.Append((char)hexNo);
i += 2;
}
else
{
sb.Append(c);
}
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
public static string UrlFormat(this string url, params string[] urlComponents)
{
var encodedUrlComponents = new string[urlComponents.Length];
for (var i = 0; i < urlComponents.Length; i++)
{
var x = urlComponents[i];
encodedUrlComponents[i] = x.UrlEncode();
}
return Format(url, encodedUrlComponents);
}
public static string ToRot13(this string value)
{
var array = value.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
var number = (int)array[i];
if (number >= 'a' && number <= 'z')
number += (number > 'm') ? -13 : 13;
else if (number >= 'A' && number <= 'Z')
number += (number > 'M') ? -13 : 13;
array[i] = (char)number;
}
return new string(array);
}
public static string WithTrailingSlash(this string path)
{
if (String.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (path[path.Length - 1] != '/')
{
return path + "/";
}
return path;
}
public static string AppendPath(this string uri, params string[] uriComponents)
{
return AppendUrlPaths(uri, uriComponents);
}
public static string AppendUrlPaths(this string uri, params string[] uriComponents)
{
var sb = StringBuilderThreadStatic.Allocate();
sb.Append(uri.WithTrailingSlash());
var i = 0;
foreach (var uriComponent in uriComponents)
{
if (i++ > 0) sb.Append('/');
sb.Append(uriComponent.UrlEncode());
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
public static string AppendUrlPathsRaw(this string uri, params string[] uriComponents)
{
var sb = StringBuilderThreadStatic.Allocate();
sb.Append(uri.WithTrailingSlash());
var i = 0;
foreach (var uriComponent in uriComponents)
{
if (i++ > 0) sb.Append('/');
sb.Append(uriComponent);
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
public static string FromUtf8Bytes(this byte[] bytes)
{
return bytes == null ? null
: Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
public static byte[] ToUtf8Bytes(this string value)
{
return Encoding.UTF8.GetBytes(value);
}
public static byte[] ToUtf8Bytes(this int intVal)
{
return FastToUtf8Bytes(intVal.ToString());
}
public static byte[] ToUtf8Bytes(this long longVal)
{
return FastToUtf8Bytes(longVal.ToString());
}
public static byte[] ToUtf8Bytes(this ulong ulongVal)
{
return FastToUtf8Bytes(ulongVal.ToString());
}
public static byte[] ToUtf8Bytes(this double doubleVal)
{
var doubleStr = doubleVal.ToString(CultureInfo.InvariantCulture.NumberFormat);
if (doubleStr.IndexOf('E') != -1 || doubleStr.IndexOf('e') != -1)
doubleStr = DoubleConverter.ToExactString(doubleVal);
return FastToUtf8Bytes(doubleStr);
}
// from JWT spec
public static string ToBase64UrlSafe(this byte[] input)
{
var output = Convert.ToBase64String(input);
output = output.LeftPart('='); // Remove any trailing '='s
output = output.Replace('+', '-'); // 62nd char of encoding
output = output.Replace('/', '_'); // 63rd char of encoding
return output;
}
// from JWT spec
public static byte[] FromBase64UrlSafe(this string input)
{
var output = input;
output = output.Replace('-', '+'); // 62nd char of encoding
output = output.Replace('_', '/'); // 63rd char of encoding
switch (output.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: output += "=="; break; // Two pad chars
case 3: output += "="; break; // One pad char
default: throw new Exception("Illegal base64url string!");
}
var converted = Convert.FromBase64String(output); // Standard base64 decoder
return converted;
}
/// <summary>
/// Skip the encoding process for 'safe strings'
/// </summary>
/// <param name="strVal"></param>
/// <returns></returns>
private static byte[] FastToUtf8Bytes(string strVal)
{
var bytes = new byte[strVal.Length];
for (var i = 0; i < strVal.Length; i++)
bytes[i] = (byte)strVal[i];
return bytes;
}
public static string LeftPart(this string strVal, char needle)
{
if (strVal == null) return null;
var pos = strVal.IndexOf(needle);
return pos == -1
? strVal
: strVal.Substring(0, pos);
}
public static string LeftPart(this string strVal, string needle)
{
if (strVal == null) return null;
var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
return pos == -1
? strVal
: strVal.Substring(0, pos);
}
public static string RightPart(this string strVal, char needle)
{
if (strVal == null) return null;
var pos = strVal.IndexOf(needle);
return pos == -1
? strVal
: strVal.Substring(pos + 1);
}
public static string RightPart(this string strVal, string needle)
{
if (strVal == null) return null;
var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
return pos == -1
? strVal
: strVal.Substring(pos + needle.Length);
}
public static string LastLeftPart(this string strVal, char needle)
{
if (strVal == null) return null;
var pos = strVal.LastIndexOf(needle);
return pos == -1
? strVal
: strVal.Substring(0, pos);
}
public static string LastLeftPart(this string strVal, string needle)
{
if (strVal == null) return null;
var pos = strVal.LastIndexOf(needle, StringComparison.OrdinalIgnoreCase);
return pos == -1
? strVal
: strVal.Substring(0, pos);
}
public static string LastRightPart(this string strVal, char needle)
{
if (strVal == null) return null;
var pos = strVal.LastIndexOf(needle);
return pos == -1
? strVal
: strVal.Substring(pos + 1);
}
public static string LastRightPart(this string strVal, string needle)
{
if (strVal == null) return null;
var pos = strVal.LastIndexOf(needle, StringComparison.OrdinalIgnoreCase);
return pos == -1
? strVal
: strVal.Substring(pos + needle.Length);
}
public static string[] SplitOnFirst(this string strVal, char needle)
{
if (strVal == null) return TypeConstants.EmptyStringArray;
var pos = strVal.IndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnFirst(this string strVal, string needle)
{
if (strVal == null) return TypeConstants.EmptyStringArray;
var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + needle.Length) };
}
public static string[] SplitOnLast(this string strVal, char needle)
{
if (strVal == null) return TypeConstants.EmptyStringArray;
var pos = strVal.LastIndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnLast(this string strVal, string needle)
{
if (strVal == null) return TypeConstants.EmptyStringArray;
var pos = strVal.LastIndexOf(needle, StringComparison.OrdinalIgnoreCase);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + needle.Length) };
}
public static string WithoutExtension(this string filePath)
{
if (String.IsNullOrEmpty(filePath))
return null;
var extPos = filePath.LastIndexOf('.');
if (extPos == -1) return filePath;
var dirPos = filePath.LastIndexOfAny(PclExport.DirSeps);
return extPos > dirPos ? filePath.Substring(0, extPos) : filePath;
}
public static string GetExtension(this string filePath)
{
if (String.IsNullOrEmpty(filePath))
return null;
var extPos = filePath.LastIndexOf('.');
return extPos == -1 ? Empty : filePath.Substring(extPos);
}
public static string ParentDirectory(this string filePath)
{
if (String.IsNullOrEmpty(filePath)) return null;
var dirSep = filePath.IndexOf(PclExport.Instance.DirSep) != -1
? PclExport.Instance.DirSep
: filePath.IndexOf(PclExport.Instance.AltDirSep) != -1
? PclExport.Instance.AltDirSep
: (char)0;
return dirSep == 0 ? null : filePath.TrimEnd(dirSep).SplitOnLast(dirSep)[0];
}
public static string ToJsv<T>(this T obj)
{
return TypeSerializer.SerializeToString(obj);
}
public static string ToSafeJsv<T>(this T obj)
{
return TypeSerializer.HasCircularReferences(obj)
? obj.ToSafePartialObjectDictionary().ToJsv()
: obj.ToJsv();
}
public static T FromJsv<T>(this string jsv)
{
return TypeSerializer.DeserializeFromString<T>(jsv);
}
public static string ToJson<T>(this T obj)
{
return JsConfig.PreferInterfaces
? JsonSerializer.SerializeToString(obj, AssemblyUtils.MainInterface<T>())
: JsonSerializer.SerializeToString(obj);
}
public static string ToSafeJson<T>(this T obj)
{
return TypeSerializer.HasCircularReferences(obj)
? obj.ToSafePartialObjectDictionary().ToJson()
: obj.ToJson();
}
public static T FromJson<T>(this string json)
{
return JsonSerializer.DeserializeFromString<T>(json);
}
public static string ToCsv<T>(this T obj)
{
return CsvSerializer.SerializeToString(obj);
}
public static T FromCsv<T>(this string csv)
{
return CsvSerializer.DeserializeFromString<T>(csv);
}
public static string FormatWith(this string text, params object[] args)
{
return Format(text, args);
}
public static string Fmt(this string text, params object[] args)
{
return Format(text, args);
}
public static string Fmt(this string text, object arg1)
{
return Format(text, arg1);
}
public static string Fmt(this string text, object arg1, object arg2)
{
return Format(text, arg1, arg2);
}
public static string Fmt(this string text, object arg1, object arg2, object arg3)
{
return Format(text, arg1, arg2, arg3);
}
public static bool StartsWithIgnoreCase(this string text, string startsWith)
{
return text != null
&& text.StartsWith(startsWith, PclExport.Instance.InvariantComparisonIgnoreCase);
}
public static bool EndsWithIgnoreCase(this string text, string endsWith)
{
return text != null
&& text.EndsWith(endsWith, PclExport.Instance.InvariantComparisonIgnoreCase);
}
public static string ReadAllText(this string filePath)
{
return PclExport.Instance.ReadAllText(filePath);
}
public static bool FileExists(this string filePath)
{
return PclExport.Instance.FileExists(filePath);
}
public static bool DirectoryExists(this string dirPath)
{
return PclExport.Instance.DirectoryExists(dirPath);
}
public static void CreateDirectory(this string dirPath)
{
PclExport.Instance.CreateDirectory(dirPath);
}
public static int IndexOfAny(this string text, params string[] needles)
{
return IndexOfAny(text, 0, needles);
}
public static int IndexOfAny(this string text, int startIndex, params string[] needles)
{
var firstPos = -1;
if (text != null)
{
foreach (var needle in needles)
{
var pos = text.IndexOf(needle, startIndex, StringComparison.Ordinal);
if (pos >= 0 && (firstPos == -1 || pos < firstPos))
firstPos = pos;
}
}
return firstPos;
}
public static string ExtractContents(this string fromText, string startAfter, string endAt)
{
return ExtractContents(fromText, startAfter, startAfter, endAt);
}
public static string ExtractContents(this string fromText, string uniqueMarker, string startAfter, string endAt)
{
if (String.IsNullOrEmpty(uniqueMarker))
throw new ArgumentNullException("uniqueMarker");
if (String.IsNullOrEmpty(startAfter))
throw new ArgumentNullException("startAfter");
if (String.IsNullOrEmpty(endAt))
throw new ArgumentNullException("endAt");
if (String.IsNullOrEmpty(fromText)) return null;
var markerPos = fromText.IndexOf(uniqueMarker);
if (markerPos == -1) return null;
var startPos = fromText.IndexOf(startAfter, markerPos);
if (startPos == -1) return null;
startPos += startAfter.Length;
var endPos = fromText.IndexOf(endAt, startPos);
if (endPos == -1) endPos = fromText.Length;
return fromText.Substring(startPos, endPos - startPos);
}
static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>", PclExport.Instance.RegexOptions);
public static string StripHtml(this string html)
{
return String.IsNullOrEmpty(html) ? null : StripHtmlRegEx.Replace(html, "");
}
public static string Quoted(this string text)
{
return text == null || text.IndexOf('"') >= 0
? text
: '"' + text + '"';
}
public static string StripQuotes(this string text)
{
return String.IsNullOrEmpty(text) || text.Length < 2
? text
: text[0] == '"' && text[text.Length - 1] == '"'
? text.Substring(1, text.Length - 2)
: text;
}
static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]", PclExport.Instance.RegexOptions);
static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)", PclExport.Instance.RegexOptions);
public static string StripMarkdownMarkup(this string markdown)
{
if (String.IsNullOrEmpty(markdown)) return null;
markdown = StripBracketsRegEx.Replace(markdown, "");
markdown = StripBracesRegEx.Replace(markdown, "");
markdown = markdown
.Replace("*", "")
.Replace("!", "")
.Replace("\r", "")
.Replace("\n", "")
.Replace("#", "");
return markdown;
}
private const int LowerCaseOffset = 'a' - 'A';
public static string ToCamelCase(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
var len = value.Length;
var newValue = new char[len];
var firstPart = true;
for (var i = 0; i < len; ++i)
{
var c0 = value[i];
var c1 = i < len - 1 ? value[i + 1] : 'A';
var c0isUpper = c0 >= 'A' && c0 <= 'Z';
var c1isUpper = c1 >= 'A' && c1 <= 'Z';
if (firstPart && c0isUpper && (c1isUpper || i == 0))
c0 = (char)(c0 + LowerCaseOffset);
else
firstPart = false;
newValue[i] = c0;
}
return new string(newValue);
}
public static string ToPascalCase(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
if (value.IndexOf('_') >= 0)
{
var parts = value.Split('_');
var sb = StringBuilderThreadStatic.Allocate();
foreach (var part in parts)
{
var str = part.ToCamelCase();
sb.Append(char.ToUpper(str[0]) + str.SafeSubstring(1, str.Length));
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
var camelCase = value.ToCamelCase();
return char.ToUpper(camelCase[0]) + camelCase.SafeSubstring(1, camelCase.Length);
}
public static string ToTitleCase(this string value)
{
return PclExport.Instance.ToTitleCase(value);
}
public static string ToLowercaseUnderscore(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
value = value.ToCamelCase();
var sb = StringBuilderThreadStatic.Allocate();
foreach (char t in value)
{
if (char.IsDigit(t) || (char.IsLetter(t) && char.IsLower(t)) || t == '_')
{
sb.Append(t);
}
else
{
sb.Append("_");
sb.Append(char.ToLowerInvariant(t));
}
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
public static string ToLowerSafe(this string value)
{
return value?.ToLower();
}
public static string ToUpperSafe(this string value)
{
return value?.ToUpper();
}
public static string SafeSubstring(this string value, int startIndex)
{
return SafeSubstring(value, startIndex, value.Length);
}
public static string SafeSubstring(this string value, int startIndex, int length)
{
if (String.IsNullOrEmpty(value)) return Empty;
if (startIndex < 0) startIndex = 0;
if (value.Length >= (startIndex + length))
return value.Substring(startIndex, length);
return value.Length > startIndex ? value.Substring(startIndex) : Empty;
}
public static string SubstringWithElipsis(this string value, int startIndex, int length)
{
var str = value.SafeSubstring(startIndex, length);
return str.Length == length
? str + "..."
: str;
}
public static bool IsAnonymousType(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return PclExport.Instance.IsAnonymousType(type);
}
public static int CompareIgnoreCase(this string strA, string strB)
{
return Compare(strA, strB, PclExport.Instance.InvariantComparisonIgnoreCase);
}
public static bool EndsWithInvariant(this string str, string endsWith)
{
return str.EndsWith(endsWith, PclExport.Instance.InvariantComparison);
}
private static readonly Regex InvalidVarCharsRegex = new Regex(@"[^A-Za-z0-9]", PclExport.Instance.RegexOptions);
private static readonly Regex SplitCamelCaseRegex = new Regex("([A-Z]|[0-9]+)", PclExport.Instance.RegexOptions);
private static readonly Regex HttpRegex = new Regex(@"^http://",
PclExport.Instance.RegexOptions | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
public static T ToEnum<T>(this string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static T ToEnumOrDefault<T>(this string value, T defaultValue)
{
if (String.IsNullOrEmpty(value)) return defaultValue;
return (T)Enum.Parse(typeof(T), value, true);
}
public static string SplitCamelCase(this string value)
{
return SplitCamelCaseRegex.Replace(value, " $1").TrimStart();
}
public static string ToInvariantUpper(this char value)
{
return PclExport.Instance.ToInvariantUpper(value);
}
public static string ToEnglish(this string camelCase)
{
var ucWords = camelCase.SplitCamelCase().ToLower();
return ucWords[0].ToInvariantUpper() + ucWords.Substring(1);
}
public static string ToHttps(this string url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
return HttpRegex.Replace(url.Trim(), "https://");
}
public static bool IsEmpty(this string value)
{
return String.IsNullOrEmpty(value);
}
public static bool IsNullOrEmpty(this string value)
{
return String.IsNullOrEmpty(value);
}
public static bool EqualsIgnoreCase(this string value, string other)
{
return String.Equals(value, other, StringComparison.CurrentCultureIgnoreCase);
}
public static string ReplaceFirst(this string haystack, string needle, string replacement)
{
var pos = haystack.IndexOf(needle, StringComparison.Ordinal);
if (pos < 0) return haystack;
return haystack.Substring(0, pos) + replacement + haystack.Substring(pos + needle.Length);
}
public static string ReplaceAll(this string haystack, string needle, string replacement)
{
int pos;
// Avoid a possible infinite loop
if (needle == replacement) return haystack;
while ((pos = haystack.IndexOf(needle, StringComparison.Ordinal)) > 0)
{
haystack = haystack.Substring(0, pos)
+ replacement
+ haystack.Substring(pos + needle.Length);
}
return haystack;
}
public static bool ContainsAny(this string text, params string[] testMatches)
{
foreach (var testMatch in testMatches)
{
if (text.Contains(testMatch)) return true;
}
return false;
}
public static string SafeVarName(this string text)
{
if (string.IsNullOrEmpty(text)) return null;
return InvalidVarCharsRegex.Replace(text, "_");
}
public static string Join(this List<string> items)
{
return string.Join(JsWriter.ItemSeperatorString, items.ToArray());
}
public static string Join(this List<string> items, string delimeter)
{
return string.Join(delimeter, items.ToArray());
}
public static string ToParentPath(this string path)
{
var pos = path.LastIndexOf('/');
if (pos == -1) return "/";
var parentPath = path.Substring(0, pos);
return parentPath;
}
public static string RemoveCharFlags(this string text, bool[] charFlags)
{
if (text == null) return null;
var copy = text.ToCharArray();
var nonWsPos = 0;
for (var i = 0; i < text.Length; i++)
{
var @char = text[i];
if (@char < charFlags.Length && charFlags[@char]) continue;
copy[nonWsPos++] = @char;
}
return new string(copy, 0, nonWsPos);
}
public static string ToNullIfEmpty(this string text)
{
return string.IsNullOrEmpty(text) ? null : text;
}
private static readonly char[] SystemTypeChars = { '<', '>', '+' };
public static bool IsUserType(this Type type)
{
return type.IsClass()
&& !type.IsSystemType();
}
public static bool IsUserEnum(this Type type)
{
return type.IsEnum()
&& !type.IsSystemType();
}
public static bool IsSystemType(this Type type)
{
return type.Namespace == null
|| type.Namespace.StartsWith("System")
|| type.Name.IndexOfAny(SystemTypeChars) >= 0;
}
public static bool IsTuple(this Type type) => type.Name.StartsWith("Tuple`");
public static bool IsInt(this string text)
{
if (string.IsNullOrEmpty(text)) return false;
int ret;
return int.TryParse(text, out ret);
}
public static int ToInt(this string text)
{
return text == null ? default(int) : Int32.Parse(text);
}
public static int ToInt(this string text, int defaultValue)
{
int ret;
return int.TryParse(text, out ret) ? ret : defaultValue;
}