-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrimitiveExtensions.cs
511 lines (468 loc) · 20.2 KB
/
PrimitiveExtensions.cs
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
#region File info
// *********************************************************************************************************
// Funcular.ExtensionMethods>Funcular.ExtensionMethods>PrimitiveExtensions.cs
// Created: 2015-07-07 12:19 AM
// Updated: 2016-07-12 9:34 AM
// By: Paul Smith
//
// *********************************************************************************************************
// LICENSE: The MIT License (MIT)
// *********************************************************************************************************
// Copyright (c) 2010-2015 Funcular Labs and Paul Smith
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// *********************************************************************************************************
#endregion
#region Usings
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
#endregion
namespace Funcular.ExtensionMethods
{
public static class PrimitiveExtensions
{
private const StringComparison COMPARISON_TYPE = StringComparison.OrdinalIgnoreCase;
private static readonly Regex _notNullOrWhitespace = new Regex(@"/^[\s]*$/", RegexOptions.Compiled);
/// <summary>
/// The negation of string.IsNullOrEmpty.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasValue(this string value)
{
return !String.IsNullOrEmpty(value);
}
/// <summary>
/// The negation of string.IsNullOrWhitespace.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNonWhitespace(this string value)
{
return !String.IsNullOrWhiteSpace(value);
}
/// <summary>
/// Returns the first non null value found.
/// </summary>
/// <param name="value"></param>
/// <param name="other"></param>
/// <returns></returns>
public static string Coalesce(this string value, string other)
{
return value.Coalesce(new[] {other});
}
/// <summary>
/// Returns the first non null value found, preferring
/// non-empty, non-whitespace values.
/// </summary>
/// <param name="value"></param>
/// <param name="others"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Coalesce(this string value, params string[] others)
{
var strings = new string[]{value}.Union(others).ToArray();
return
strings.FirstOrDefault(s => s.IsNonWhitespace())
?? strings.FirstOrDefault(s => s.HasValue())
?? strings.FirstOrDefault(s => s != null);
}
/// <summary>
/// Returns the first non null value found.
/// </summary>
/// <param name="value"></param>
/// <param name="others"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Coalesce(this decimal? value, params decimal?[] others)
{
if (value.HasValue)
return value.Value;
decimal? tmp;
return (others == null || others.Length == 0)
? default(decimal)
: (tmp = (others.FirstOrDefault(arg => arg.HasValue))).HasValue ? tmp.Value : default(decimal);
}
public static string TrimOrEmpty(this string value)
{
return (value ?? String.Empty).Trim();
}
/// <summary>
/// Returns true if string <paramref name="value" /> contains any of <paramref name="others" /> (case-insensitive).
/// </summary>
/// <param name="value"></param>
/// <param name="others"></param>
/// <returns></returns>
[Obsolete("Replaced with `IsContainedByAny`; will be deprecated in a future release.", false)]
public static bool ContainsAny(this string value, params string[] others)
{
return others.HasContents() && value.HasValue() &&
others.Any(s => value.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="stringComparison"></param>
/// <param name="others"></param>
/// <returns></returns>
[Obsolete("Replaced with `IsContainedByAny`; will be deprecated in a future release.", false)]
public static bool ContainsAny(this string value, StringComparison stringComparison, params string[] others)
{
return others.HasContents() && value.HasValue() &&
others.Any(s => value.IndexOf(s, stringComparison) >= 0);
}
/// <summary>
/// Returns true if string <paramref name="value" /> contains any of <paramref name="others" /> (case-insensitive).
/// </summary>
/// <param name="value"></param>
/// <param name="others"></param>
/// <returns></returns>
public static bool IsContainedByAny(this string value, params string[] others)
{
return others.HasContents() && value.HasValue() &&
others.Any(s => value.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="stringComparison"></param>
/// <param name="others"></param>
/// <returns></returns>
public static bool IsContainedByAny(this string value, StringComparison stringComparison, params string[] others)
{
return others.HasContents() && value.HasValue() &&
others.Any(s => value.IndexOf(s, stringComparison) >= 0);
}
/// <summary>
/// Returns true if <paramref name="values" /> contain <paramref name="sought" />, used to
/// perform case-insensitive searches in arrays.
/// </summary>
/// <param name="values"></param>
/// <param name="sought"></param>
/// <param name="caseSensitive"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Contains(this string[] values, string sought, bool caseSensitive)
{
return caseSensitive
? values.AsQueryable().Any(s => s == sought)
: values.AsQueryable().Any(s => s.Equals(sought, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// This signature is on almost every other string.comparision method, but they
/// left it out for .Contains. It is long-overdue justice that we restore it now.
/// Returns false if either string is null.
/// </summary>
/// <param name="value"></param>
/// <param name="find"></param>
/// <param name="comparison"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Contains(this string value, string find, StringComparison comparison)
{
if (value == null || find == null)
return false;
return value.IndexOf(find, comparison) >= 0;
}
/// <summary>
/// Returns true if <paramref name="value" /> is any of <paramref name="others" /> (case-insensitive).
/// </summary>
/// <param name="value"></param>
/// <param name="others"></param>
/// <returns></returns>
public static bool IsIn(this string value, params string[] others)
{
if (others.HasContents() && value != null)
return others.Any(s => s.Equals(value, COMPARISON_TYPE));
return false;
}
/// <summary>
/// Recursively remove all occurrences of <paramref name="needle" /> from <paramref name="haystack" />.
/// </summary>
/// <param name="haystack"></param>
/// <param name="needle"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string ReplaceAll(this string haystack, string needle, string replacement)
{
while (haystack.IndexOf(needle, COMPARISON_TYPE) > -1)
haystack = haystack.Replace(needle, replacement);
return haystack;
}
/// <summary>
/// Returns a string comprised of only the digits in <paramref name="incomingNumber" />
/// </summary>
/// <param name="incomingNumber"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string ToNumericString(this string incomingNumber)
{
if (!incomingNumber.HasValue())
return incomingNumber;
return String.Join("", incomingNumber.Split(incomingNumber
.Where(c => !Char.IsNumber(c))
.Distinct()
.ToArray()));
}
/// <summary>
/// If <paramref name="value" /> does not end with <paramref name="endWith" />, appends it.
/// </summary>
/// <param name="value"></param>
/// <param name="endWith"></param>
/// <returns></returns>
public static string EnsureEndsWith(this string value, string endWith)
{
return value.EndsWith(endWith) ? value : value + endWith;
}
/// <summary>
/// If <paramref name="value" /> does not start with <paramref name="startWith" />, prepends it.
/// </summary>
/// <param name="value"></param>
/// <param name="startWith"></param>
/// <returns></returns>
public static string EnsureStartsWith(this string value, string startWith)
{
return value.StartsWith(startWith) ? value : startWith + value;
}
/// <summary>
/// If <paramref name="originalString" /> contains <paramref name="ofString" />, returns everything before
/// <paramref name="ofString" />.
/// Returns an empty string in all other cases.
/// </summary>
/// <param name="originalString"></param>
/// <param name="ofString"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string LeftOfFirst(this string originalString, string ofString)
{
if (String.IsNullOrEmpty(originalString))
return String.Empty;
var idx = originalString.IndexOf(ofString, StringComparison.OrdinalIgnoreCase);
return (idx >= 0 ? originalString.Substring(0, idx) : String.Empty);
}
/// <summary>
/// If <paramref name="originalString" /> contains <paramref name="ofString" />, returns the text to the right of it.
/// Otherwise returns the full string.
/// </summary>
/// <param name="originalString"></param>
/// <param name="ofString"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string LeftOfLast(this string originalString, string ofString)
{
if (String.IsNullOrEmpty(originalString))
return String.Empty;
var idx = originalString.LastIndexOf(ofString, StringComparison.OrdinalIgnoreCase);
return (idx >= 0 ? originalString.Substring(0, idx) : String.Empty);
}
/// <summary>
/// If <paramref name="originalString" /> contains <paramref name="ofString" />, returns the portion after the last
/// occurrence.
/// If not, returns an empty string.
/// </summary>
/// <param name="originalString"></param>
/// <param name="ofString"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string RightOfLast(this string originalString, string ofString)
{
if (String.IsNullOrEmpty(originalString))
return String.Empty;
var idx = originalString.LastIndexOf(ofString, StringComparison.OrdinalIgnoreCase);
return (idx < 0
? String.Empty
: originalString.Substring(idx + ofString.Length, originalString.Length - (idx + ofString.Length)));
}
/// <summary>
/// If <paramref name="originalString" /> contains <paramref name="ofString" />, returns the portion after the first
/// occurrence.
/// If not, returns empty string.
/// </summary>
/// <param name="originalString"></param>
/// <param name="ofString"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string RightOfFirst(this string originalString, string ofString)
{
if (String.IsNullOrEmpty(originalString))
return String.Empty;
var idx = originalString.IndexOf(ofString, StringComparison.OrdinalIgnoreCase);
return (idx < 0
? String.Empty
: originalString.Substring(idx + ofString.Length));
}
/// <summary>
/// Truncates the string if it exceeds the max length
/// </summary>
/// <param name="value"></param>
/// <param name="maxLength"></param>
/// <returns></returns>
public static string Truncate(this string value, int maxLength)
{
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
/// <summary>
/// If value ends with digits, returns as many ending characters as are digits,
/// otherwise, returns -1.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetIntegerSuffix(this string value)
{
var ret = -1;
if (!String.IsNullOrWhiteSpace(value))
{
var sb = new StringBuilder();
var chars = value.ToCharArray();
for (var i = chars.Length - 1; i >= 0; i--)
{
if (Char.IsDigit(chars[i]))
sb.Insert(0, chars[i]);
else
break;
}
int parsed;
if (Int32.TryParse(sb.ToString(), out parsed))
ret = parsed;
}
return ret;
}
/// <summary>
/// If value is all digits and >= 0, returns true, otherwise false.
/// </summary>
public static bool IsPositiveInteger(this string value)
{
if (String.IsNullOrWhiteSpace(value))
return false;
var chars = value.ToCharArray();
return chars.All(c => (Char.IsDigit(c) && c != '-'));
}
/// <summary>
/// True if value without spaces is all digits, or a decimal place, comma, minus sign or dollar sign, otherwise false.
/// </summary>
public static bool IsNumeric(this string value)
{
if (String.IsNullOrEmpty(value))
return false;
value = value.Replace(" ", "");
var chars = value.ToCharArray();
return chars.All(c => Char.IsDigit(c) || c.ToString().IsIn(".", ",", "$", "-"));
}
/// <summary>
/// If value is 5 or 9 digits (plus dash), returns true, otherwise false.
/// </summary>
public static bool IsUsZipCode(this string value)
{
if (String.IsNullOrWhiteSpace(value))
return false;
value = value.Replace(" ", "").Replace("-", "");
return (new[] {5, 9}).Contains(value.Length) && value.ToCharArray().All(Char.IsDigit);
}
/// <summary>
/// If fractional component is greater than 0, rounds value up to the next integer
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int RoundUp(this decimal value)
{
var mod = value%1;
return (int) (mod == 0 ? value : Math.Truncate(value) + 1);
}
/// <summary>
/// Rounds value down to its integer component
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int RoundDown(this decimal value)
{
return (int) Math.Truncate(value);
}
/// <summary>
/// Convert this array of bytes to a hexadecimal string.
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string ToHex(this byte[] bytes)
{
if (!bytes.HasContents())
return String.Empty;
var hex = BitConverter.ToString(bytes);
return hex.Replace("-", "");
}
/// <summary>
/// How many billionths (1/1,000,000,000) of a second <paramref name="interval" /> represents.
/// </summary>
/// <param name="interval"></param>
/// <returns></returns>
public static long TotalNanoseconds(this TimeSpan interval)
{
return (long) (interval.TotalMilliseconds*1000000.0000);
}
/// <summary>
/// How many millionths (1/1,000,000) of a second <paramref name="interval" /> represents.
/// </summary>
/// <param name="interval"></param>
/// <returns></returns>
public static long TotalMicroseconds(this TimeSpan interval)
{
return (long) (interval.TotalMilliseconds*1000.0000);
}
/// <summary>
/// Returns a 64 bit integer <= <paramref name="max"/>.
/// </summary>
/// <param name="rand"></param>
/// <param name="max"></param>
/// <returns></returns>
public static long NextLong(this Random rand, long max)
{
var buf = new byte[8];
rand.NextBytes(buf);
var longRand = BitConverter.ToInt64(buf, 0);
return (Math.Abs(longRand%max));
}
/// <summary>
/// Returns a 64 bit integer between <paramref name="min"/> and
/// <paramref name="max"/> inclusive.
/// </summary>
/// <param name="rand"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static long NextLong(this Random rand, long min, long max)
{
var buf = new byte[8];
rand.NextBytes(buf);
var longRand = BitConverter.ToInt64(buf, 0);
return (Math.Abs(longRand%(max - min)) + min);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DateTime ToDateTime(this string val)
{
val = val.Trim();
return val.Length == 8 ? (DateTime.ParseExact(val, "yyyyMMdd", CultureInfo.CurrentCulture)) : DateTime.Parse(val);
}
}
}