-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
ImTools.cs
1973 lines (1685 loc) · 85 KB
/
ImTools.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
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
// <auto-generated/>
/*
The MIT License (MIT)
Copyright (c) 2016-2018 Maksim Volkau
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 AddOrUpdateServiceFactory
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.
*/
namespace ImTools
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices; // For [MethodImpl(AggressiveInlining)]
/// <summary>Helpers for functional composition</summary>
public static class Fun
{
/// <summary>Always a true condition.</summary>
public static bool Always<T>(T _) => true;
/// <summary>Identity function returning passed argument as result.</summary>
public static T Id<T>(T x) => x;
/// <summary>Piping</summary>
public static R To<T, R>(this T x, Func<T, R> map) => map(x);
/// <summary>Piping</summary>
public static void Do<T>(this T x, Action<T> effect) => effect(x);
/// Lift argument to Func without allocations ignoring the first argument.
/// For example if you have `Func{T, R} = _ => instance`,
/// you may rewrite it without allocations as `instance.ToFunc{A, R}`
public static R ToFunc<T, R>(this R result, T ignoredArg) => result;
}
/// <summary>Helpers for lazy instantiations</summary>
public static class Lazy
{
/// <summary>Provides result type inference for creation of lazy.</summary>
public static Lazy<T> Of<T>(Func<T> valueFactory) => new Lazy<T>(valueFactory);
}
/// <summary>Methods to work with immutable arrays and some sugar.</summary>
public static class ArrayTools
{
private static class EmptyArray<T>
{
public static readonly T[] Value = new T[0];
}
/// <summary>Returns singleton empty array of provided type.</summary>
/// <typeparam name="T">Array item type.</typeparam> <returns>Empty array.</returns>
public static T[] Empty<T>() => EmptyArray<T>.Value;
/// <summary>Wraps item in array.</summary>
public static T[] One<T>(this T one) => new[] { one };
/// <summary>Returns true if array is null or have no items.</summary> <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Source array to check.</param> <returns>True if null or has no items, false otherwise.</returns>
public static bool IsNullOrEmpty<T>(this T[] source) => source == null || source.Length == 0;
/// <summary>Returns empty array instead of null, or source array otherwise.</summary> <typeparam name="T">Type of array item.</typeparam>
public static T[] EmptyIfNull<T>(this T[] source) => source ?? Empty<T>();
/// Returns source enumerable if it is array, otherwise converts source to array or an empty array if null.
public static T[] ToArrayOrSelf<T>(this IEnumerable<T> source) =>
source == null ? Empty<T>() : (source as T[] ?? source.ToArray());
/// Returns source enumerable if it is list, otherwise converts source to IList or an empty array if null.
public static IList<T> ToListOrSelf<T>(this IEnumerable<T> source) =>
source == null ? Empty<T>() : source as IList<T> ?? source.ToList();
/// <summary>Returns new array consisting from all items from source array then all items from added array.
/// If source is null or empty, then added array will be returned.
/// If added is null or empty, then source will be returned.</summary>
/// <typeparam name="T">Array item type.</typeparam>
/// <param name="source">Array with leading items.</param>
/// <param name="added">Array with following items.</param>
/// <returns>New array with items of source and added arrays.</returns>
public static T[] Append<T>(this T[] source, params T[] added)
{
if (added == null || added.Length == 0)
return source;
if (source == null || source.Length == 0)
return added;
var result = new T[source.Length + added.Length];
Array.Copy(source, 0, result, 0, source.Length);
if (added.Length == 1)
result[source.Length] = added[0];
else
Array.Copy(added, 0, result, source.Length, added.Length);
return result;
}
/// <summary>Performant concat of enumerables in case of arrays.
/// But performance will degrade if you use Concat().Where().</summary>
/// <typeparam name="T">Type of item.</typeparam>
/// <param name="source">goes first.</param>
/// <param name="other">appended to source.</param>
/// <returns>empty array or concat of source and other.</returns>
public static T[] Append<T>(this IEnumerable<T> source, IEnumerable<T> other) =>
source.ToArrayOrSelf().Append(other.ToArrayOrSelf());
/// <summary>Returns new array with <paramref name="value"/> appended,
/// or <paramref name="value"/> at <paramref name="index"/>, if specified.
/// If source array could be null or empty, then single value item array will be created despite any index.</summary>
/// <typeparam name="T">Array item type.</typeparam>
/// <param name="source">Array to append value to.</param>
/// <param name="value">Value to append.</param>
/// <param name="index">(optional) Index of value to update.</param>
/// <returns>New array with appended or updated value.</returns>
public static T[] AppendOrUpdate<T>(this T[] source, T value, int index = -1)
{
if (source == null || source.Length == 0)
return new[] { value };
var sourceLength = source.Length;
index = index < 0 ? sourceLength : index;
var result = new T[index < sourceLength ? sourceLength : sourceLength + 1];
Array.Copy(source, result, sourceLength);
result[index] = value;
return result;
}
/// <summary>Calls predicate on each item in <paramref name="source"/> array until predicate returns true,
/// then method will return this item index, or if predicate returns false for each item, method will return -1.</summary>
/// <typeparam name="T">Type of array items.</typeparam>
/// <param name="source">Source array: if null or empty, then method will return -1.</param>
/// <param name="predicate">Delegate to evaluate on each array item until delegate returns true.</param>
/// <returns>Index of item for which predicate returns true, or -1 otherwise.</returns>
public static int IndexOf<T>(this T[] source, Func<T, bool> predicate)
{
if (source != null && source.Length != 0)
for (var i = 0; i < source.Length; ++i)
if (predicate(source[i]))
return i;
return -1;
}
/// <summary>Looks up for item in source array equal to provided value, and returns its index, or -1 if not found.</summary>
/// <typeparam name="T">Type of array items.</typeparam>
/// <param name="source">Source array: if null or empty, then method will return -1.</param>
/// <param name="value">Value to look up.</param>
/// <returns>Index of item equal to value, or -1 item is not found.</returns>
public static int IndexOf<T>(this T[] source, T value)
{
if (source != null && source.Length != 0)
for (var i = 0; i < source.Length; ++i)
{
var item = source[i];
if (Equals(item, value))
return i;
}
return -1;
}
/// <summary>Produces new array without item at specified <paramref name="index"/>.
/// Will return <paramref name="source"/> array if index is out of bounds, or source is null/empty.</summary>
/// <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Input array.</param> <param name="index">Index if item to remove.</param>
/// <returns>New array with removed item at index, or input source array if index is not in array.</returns>
public static T[] RemoveAt<T>(this T[] source, int index)
{
if (source == null || source.Length == 0 || index < 0 || index >= source.Length)
return source;
if (index == 0 && source.Length == 1)
return new T[0];
var result = new T[source.Length - 1];
if (index != 0)
Array.Copy(source, 0, result, 0, index);
if (index != result.Length)
Array.Copy(source, index + 1, result, index, result.Length - index);
return result;
}
/// <summary>Looks for item in array using equality comparison, and returns new array with found item remove, or original array if not item found.</summary>
/// <typeparam name="T">Type of array item.</typeparam>
/// <param name="source">Input array.</param> <param name="value">Value to find and remove.</param>
/// <returns>New array with value removed or original array if value is not found.</returns>
public static T[] Remove<T>(this T[] source, T value) =>
source.RemoveAt(source.IndexOf(value));
/// <summary>Returns first item matching the <paramref name="predicate"/>, or default item value.</summary>
/// <typeparam name="T">item type</typeparam>
/// <param name="source">items collection to search</param>
/// <param name="predicate">condition to evaluate for each item.</param>
/// <returns>First item matching condition or default value.</returns>
public static T FindFirst<T>(this T[] source, Func<T, bool> predicate)
{
if (source != null && source.Length != 0)
for (var i = 0; i < source.Length; ++i)
{
var item = source[i];
if (predicate(item))
return item;
}
return default(T);
}
/// Version of FindFirst with the fixed state used by predicate to prevent allocations by predicate lambda closure
public static T FindFirst<T, S>(this T[] source, S state, Func<S, T, bool> predicate)
{
if (source != null && source.Length != 0)
for (var i = 0; i < source.Length; ++i)
{
var item = source[i];
if (predicate(state, item))
return item;
}
return default(T);
}
/// <summary>Returns first item matching the <paramref name="predicate"/>, or default item value.</summary>
/// <typeparam name="T">item type</typeparam>
/// <param name="source">items collection to search</param>
/// <param name="predicate">condition to evaluate for each item.</param>
/// <returns>First item matching condition or default value.</returns>
public static T FindFirst<T>(this IEnumerable<T> source, Func<T, bool> predicate) =>
source is T[] sourceArr ? sourceArr.FindFirst(predicate) : source.FirstOrDefault(predicate);
/// <summary>Returns element if collection consist on single element, otherwise returns default value.
/// It does not throw for collection with many elements</summary>
public static T SingleOrDefaultIfMany<T>(this IEnumerable<T> source)
{
if (source is IList<T> list)
return list.Count == 1 ? list[0] : default(T);
if (source == null)
return default(T);
using (var e = source.GetEnumerator())
{
if (!e.MoveNext())
return default(T);
var it = e.Current;
return !e.MoveNext() ? it : default(T);
}
}
/// <summary>Does <paramref name="action"/> for each item</summary>
public static void ForEach<T>(this T[] source, Action<T> action)
{
if (!source.IsNullOrEmpty())
for (var i = 0; i < source.Length; i++)
action(source[i]);
}
/// Appends source to results
public static T[] AppendTo<T>(T[] source, int sourcePos, int count, T[] results = null)
{
if (results == null)
{
var newResults = new T[count];
if (count == 1)
newResults[0] = source[sourcePos];
else
for (int i = 0, j = sourcePos; i < count; ++i, ++j)
newResults[i] = source[j];
return newResults;
}
var matchCount = results.Length;
var appendedResults = new T[matchCount + count];
if (matchCount == 1)
appendedResults[0] = results[0];
else
Array.Copy(results, 0, appendedResults, 0, matchCount);
if (count == 1)
appendedResults[matchCount] = source[sourcePos];
else
Array.Copy(source, sourcePos, appendedResults, matchCount, count);
return appendedResults;
}
private static R[] AppendTo<T, R>(T[] source, int sourcePos, int count, Func<T, R> map, R[] results = null)
{
if (results == null || results.Length == 0)
{
var newResults = new R[count];
if (count == 1)
newResults[0] = map(source[sourcePos]);
else
for (int i = 0, j = sourcePos; i < count; ++i, ++j)
newResults[i] = map(source[j]);
return newResults;
}
var oldResultsCount = results.Length;
var appendedResults = new R[oldResultsCount + count];
if (oldResultsCount == 1)
appendedResults[0] = results[0];
else
Array.Copy(results, 0, appendedResults, 0, oldResultsCount);
if (count == 1)
appendedResults[oldResultsCount] = map(source[sourcePos]);
else
{
for (int i = oldResultsCount, j = sourcePos; i < appendedResults.Length; ++i, ++j)
appendedResults[i] = map(source[j]);
}
return appendedResults;
}
private static R[] AppendTo<T, S, R>(T[] source, S state, int sourcePos, int count, Func<S, T, R> map, R[] results = null)
{
if (results == null || results.Length == 0)
{
var newResults = new R[count];
if (count == 1)
newResults[0] = map(state, source[sourcePos]);
else
for (int i = 0, j = sourcePos; i < count; ++i, ++j)
newResults[i] = map(state, source[j]);
return newResults;
}
var oldResultsCount = results.Length;
var appendedResults = new R[oldResultsCount + count];
if (oldResultsCount == 1)
appendedResults[0] = results[0];
else
Array.Copy(results, 0, appendedResults, 0, oldResultsCount);
if (count == 1)
appendedResults[oldResultsCount] = map(state, source[sourcePos]);
else
{
for (int i = oldResultsCount, j = sourcePos; i < appendedResults.Length; ++i, ++j)
appendedResults[i] = map(state, source[j]);
}
return appendedResults;
}
/// <summary>Where method similar to Enumerable.Where but more performant and non necessary allocating.
/// It returns source array and does Not create new one if all items match the condition.</summary>
/// <typeparam name="T">Type of source items.</typeparam>
/// <param name="source">If null, the null will be returned.</param>
/// <param name="condition">Condition to keep items.</param>
/// <returns>New array if some items are filter out. Empty array if all items are filtered out. Original array otherwise.</returns>
public static T[] Match<T>(this T[] source, Func<T, bool> condition)
{
if (source == null || source.Length == 0)
return source;
if (source.Length == 1)
return condition(source[0]) ? source : Empty<T>();
if (source.Length == 2)
{
var condition0 = condition(source[0]);
var condition1 = condition(source[1]);
return condition0 && condition1 ? new[] { source[0], source[1] }
: condition0 ? new[] { source[0] }
: condition1 ? new[] { source[1] }
: Empty<T>();
}
var matchStart = 0;
T[] matches = null;
var matchFound = false;
var i = 0;
for (; i < source.Length; ++i)
if (!(matchFound = condition(source[i])))
{
// for accumulated matched items
if (i != 0 && i > matchStart)
matches = AppendTo(source, matchStart, i - matchStart, matches);
matchStart = i + 1; // guess the next match start will be after the non-matched item
}
// when last match was found but not all items are matched (hence matchStart != 0)
if (matchFound && matchStart != 0)
return AppendTo(source, matchStart, i - matchStart, matches);
return matches ?? (matchStart != 0 ? Empty<T>() : source);
}
/// Match with the additional state to use in <paramref name="condition"/> to minimize the allocations in <paramref name="condition"/> lambda closure
public static T[] Match<T, S>(this T[] source, S state, Func<S, T, bool> condition)
{
if (source == null || source.Length == 0)
return source;
if (source.Length == 1)
return condition(state, source[0]) ? source : Empty<T>();
if (source.Length == 2)
{
var condition0 = condition(state, source[0]);
var condition1 = condition(state, source[1]);
return condition0 && condition1 ? new[] { source[0], source[1] }
: condition0 ? new[] { source[0] }
: condition1 ? new[] { source[1] }
: Empty<T>();
}
var matchStart = 0;
T[] matches = null;
var matchFound = false;
var i = 0;
for (; i < source.Length; ++i)
if (!(matchFound = condition(state, source[i])))
{
// for accumulated matched items
if (i != 0 && i > matchStart)
matches = AppendTo(source, matchStart, i - matchStart, matches);
matchStart = i + 1; // guess the next match start will be after the non-matched item
}
// when last match was found but not all items are matched (hence matchStart != 0)
if (matchFound && matchStart != 0)
return AppendTo(source, matchStart, i - matchStart, matches);
return matches ?? (matchStart != 0 ? Empty<T>() : source);
}
/// <summary>Where method similar to Enumerable.Where but more performant and non necessary allocating.
/// It returns source array and does Not create new one if all items match the condition.</summary>
/// <typeparam name="T">Type of source items.</typeparam> <typeparam name="R">Type of result items.</typeparam>
/// <param name="source">If null, the null will be returned.</param>
/// <param name="condition">Condition to keep items.</param> <param name="map">Converter from source to result item.</param>
/// <returns>New array of result items.</returns>
public static R[] Match<T, R>(this T[] source, Func<T, bool> condition, Func<T, R> map)
{
if (source == null)
return null;
if (source.Length == 0)
return Empty<R>();
if (source.Length == 1)
{
var item = source[0];
return condition(item) ? new[] { map(item) } : Empty<R>();
}
if (source.Length == 2)
{
var condition0 = condition(source[0]);
var condition1 = condition(source[1]);
return condition0 && condition1 ? new[] { map(source[0]), map(source[1]) }
: condition0 ? new[] { map(source[0]) }
: condition1 ? new[] { map(source[1]) }
: Empty<R>();
}
var matchStart = 0;
R[] matches = null;
var matchFound = false;
var i = 0;
for (; i < source.Length; ++i)
if (!(matchFound = condition(source[i])))
{
// for accumulated matched items
if (i != 0 && i > matchStart)
matches = AppendTo(source, matchStart, i - matchStart, map, matches);
matchStart = i + 1; // guess the next match start will be after the non-matched item
}
// when last match was found but not all items are matched (hence matchStart != 0)
if (matchFound && matchStart != 0)
return AppendTo(source, matchStart, i - matchStart, map, matches);
return matches ?? (matchStart == 0 ? AppendTo(source, 0, source.Length, map) : Empty<R>());
}
/// Match with the additional state to use in <paramref name="condition"/> and <paramref name="map"/> to minimize the allocations in <paramref name="condition"/> lambda closure
public static R[] Match<T, S, R>(this T[] source, S state, Func<S, T, bool> condition, Func<S, T, R> map)
{
if (source == null)
return null;
if (source.Length == 0)
return Empty<R>();
if (source.Length == 1)
{
var item = source[0];
return condition(state, item) ? new[] { map(state, item) } : Empty<R>();
}
if (source.Length == 2)
{
var condition0 = condition(state, source[0]);
var condition1 = condition(state, source[1]);
return condition0 && condition1 ? new[] { map(state, source[0]), map(state, source[1]) }
: condition0 ? new[] { map(state, source[0]) }
: condition1 ? new[] { map(state, source[1]) }
: Empty<R>();
}
var matchStart = 0;
R[] matches = null;
var matchFound = false;
var i = 0;
for (; i < source.Length; ++i)
if (!(matchFound = condition(state, source[i])))
{
// for accumulated matched items
if (i != 0 && i > matchStart)
matches = AppendTo(source, state, matchStart, i - matchStart, map, matches);
matchStart = i + 1; // guess the next match start will be after the non-matched item
}
// when last match was found but not all items are matched (hence matchStart != 0)
if (matchFound && matchStart != 0)
return AppendTo(source, state, matchStart, i - matchStart, map, matches);
return matches ?? (matchStart == 0 ? AppendTo(source, state, 0, source.Length, map) : Empty<R>());
}
/// <summary>Maps all items from source to result array.</summary>
/// <typeparam name="T">Source item type</typeparam> <typeparam name="R">Result item type</typeparam>
/// <param name="source">Source items</param> <param name="map">Function to convert item from source to result.</param>
/// <returns>Converted items</returns>
public static R[] Map<T, R>(this T[] source, Func<T, R> map)
{
if (source == null)
return null;
var sourceCount = source.Length;
if (sourceCount == 0)
return Empty<R>();
if (sourceCount == 1)
return new[] { map(source[0]) };
if (sourceCount == 2)
return new[] { map(source[0]), map(source[1]) };
var results = new R[sourceCount];
for (var i = 0; i < source.Length; i++)
results[i] = map(source[i]);
return results;
}
/// Map with additional state to use in <paramref name="map"/> to minimize allocations in <paramref name="map"/> lambda closure
public static R[] Map<T, S, R>(this T[] source, S state, Func<S, T, R> map)
{
if (source == null)
return null;
var sourceCount = source.Length;
if (sourceCount == 0)
return Empty<R>();
if (sourceCount == 1)
return new[] { map(state, source[0]) };
if (sourceCount == 2)
return new[] { map(state, source[0]), map(state, source[1]) };
var results = new R[sourceCount];
for (var i = 0; i < source.Length; i++)
results[i] = map(state, source[i]);
return results;
}
/// <summary>Maps all items from source to result collection.
/// If possible uses fast array Map otherwise Enumerable.Select.</summary>
/// <typeparam name="T">Source item type</typeparam> <typeparam name="R">Result item type</typeparam>
/// <param name="source">Source items</param> <param name="map">Function to convert item from source to result.</param>
/// <returns>Converted items</returns>
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> source, Func<T, R> map) =>
source is T[] arr ? arr.Map(map) : source?.Select(map);
/// <summary>If <paramref name="source"/> is array uses more effective Match for array, otherwise just calls Where</summary>
/// <typeparam name="T">Type of source items.</typeparam>
/// <param name="source">If null, the null will be returned.</param>
/// <param name="condition">Condition to keep items.</param>
/// <returns>Result items, may be an array.</returns>
public static IEnumerable<T> Match<T>(this IEnumerable<T> source, Func<T, bool> condition) =>
source is T[] arr ? arr.Match(condition) : source?.Where(condition);
/// <summary>If <paramref name="source"/> is array uses more effective Match for array,
/// otherwise just calls Where, Select</summary>
/// <typeparam name="T">Type of source items.</typeparam> <typeparam name="R">Type of result items.</typeparam>
/// <param name="source">If null, the null will be returned.</param>
/// <param name="condition">Condition to keep items.</param> <param name="map">Converter from source to result item.</param>
/// <returns>Result items, may be an array.</returns>
public static IEnumerable<R> Match<T, R>(this IEnumerable<T> source, Func<T, bool> condition, Func<T, R> map) =>
source is T[] arr ? arr.Match(condition, map) : source?.Where(condition).Select(map);
}
/// <summary>Wrapper that provides optimistic-concurrency Swap operation implemented using <see cref="Ref.Swap{T}"/>.</summary>
/// <typeparam name="T">Type of object to wrap.</typeparam>
public sealed class Ref<T> where T : class
{
/// <summary>Gets the wrapped value.</summary>
public T Value => _value;
/// <summary>Creates ref to object, optionally with initial value provided.</summary>
/// <param name="initialValue">(optional) Initial value.</param>
public Ref(T initialValue = default(T))
{
_value = initialValue;
}
/// <summary>Exchanges currently hold object with <paramref name="getNewValue"/> - see <see cref="Ref.Swap{T}"/> for details.</summary>
/// <param name="getNewValue">Delegate to produce new object value from current one passed as parameter.</param>
/// <returns>Returns old object value the same way as <see cref="Interlocked.Exchange(ref int,int)"/></returns>
/// <remarks>Important: <paramref name="getNewValue"/> May be called multiple times to retry update with value concurrently changed by other code.</remarks>
public T Swap(Func<T, T> getNewValue) => Ref.Swap(ref _value, getNewValue);
/// Option without allocation for capturing `a` in closure of `getNewValue`
public T Swap<A>(A a, Func<A, T, T> getNewValue) => Ref.Swap(ref _value, a, getNewValue);
/// Option without allocation for capturing `a` and `b` in closure of `getNewValue`
public T Swap<A, B>(A a, B b, Func<A, B, T, T> getNewValue) => Ref.Swap(ref _value, a, b, getNewValue);
/// <summary>Just sets new value ignoring any intermingled changes.</summary>
/// <param name="newValue"></param> <returns>old value</returns>
public T Swap(T newValue) =>
Interlocked.Exchange(ref _value, newValue);
/// <summary>Compares current Referred value with <paramref name="currentValue"/> and if equal replaces current with <paramref name="newValue"/></summary>
/// <param name="currentValue"></param> <param name="newValue"></param>
/// <returns>True if current value was replaced with new value, and false if current value is outdated (already changed by other party).</returns>
/// <example><c>[!CDATA[
/// var value = SomeRef.Value;
/// if (!SomeRef.TrySwapIfStillCurrent(value, Update(value))
/// SomeRef.Swap(v => Update(v)); // fallback to normal Swap with delegate allocation
/// ]]</c></example>
public bool TrySwapIfStillCurrent(T currentValue, T newValue) =>
Interlocked.CompareExchange(ref _value, newValue, currentValue) == currentValue;
private T _value;
}
/// <summary>Provides optimistic-concurrency consistent <see cref="Swap{T}"/> operation.</summary>
public static class Ref
{
/// <summary>Factory for <see cref="Ref{T}"/> with type of value inference.</summary>
/// <typeparam name="T">Type of value to wrap.</typeparam>
/// <param name="value">Initial value to wrap.</param>
/// <returns>New ref.</returns>
public static Ref<T> Of<T>(T value) where T : class => new Ref<T>(value);
/// <summary>Creates new ref to the value of original ref.</summary> <typeparam name="T">Ref value type.</typeparam>
/// <param name="original">Original ref.</param> <returns>New ref to original value.</returns>
public static Ref<T> NewRef<T>(this Ref<T> original) where T : class => Of(original.Value);
/// <summary>First, it evaluates new value using <paramref name="getNewValue"/> function.
/// Second, it checks that original value is not changed.
/// If it is changed it will retry first step, otherwise it assigns new value and returns original (the one used for <paramref name="getNewValue"/>).</summary>
/// <typeparam name="T">Type of value to swap.</typeparam>
/// <param name="value">Reference to change to new value</param>
/// <param name="getNewValue">Delegate to get value from old one.</param>
/// <returns>Old/original value. By analogy with <see cref="Interlocked.Exchange(ref int,int)"/>.</returns>
/// <remarks>Important: <paramref name="getNewValue"/> May be called multiple times to retry update with value concurrently changed by other code.</remarks>
public static T Swap<T>(ref T value, Func<T, T> getNewValue) where T : class
{
var retryCount = 0;
while (true)
{
var oldValue = value;
var newValue = getNewValue(oldValue);
if (Interlocked.CompareExchange(ref value, newValue, oldValue) == oldValue)
return oldValue;
if (++retryCount > RETRY_COUNT_UNTIL_THROW)
throw new InvalidOperationException(_errorRetryCountExceeded);
}
}
/// Option without allocation for capturing `a` in closure of `getNewValue`
public static T Swap<A, T>(ref T value, A a, Func<A, T, T> getNewValue) where T : class
{
var retryCount = 0;
while (true)
{
var oldValue = value;
var newValue = getNewValue(a, oldValue);
if (Interlocked.CompareExchange(ref value, newValue, oldValue) == oldValue)
return oldValue;
if (++retryCount > RETRY_COUNT_UNTIL_THROW)
throw new InvalidOperationException(_errorRetryCountExceeded);
}
}
/// Option without allocation for capturing `a` and `b` in closure of `getNewValue`
public static T Swap<A, B, T>(ref T value, A a, B b, Func<A, B, T, T> getNewValue) where T : class
{
var retryCount = 0;
while (true)
{
var oldValue = value;
var newValue = getNewValue(a, b, oldValue);
if (Interlocked.CompareExchange(ref value, newValue, oldValue) == oldValue)
return oldValue;
if (++retryCount > RETRY_COUNT_UNTIL_THROW)
throw new InvalidOperationException(_errorRetryCountExceeded);
}
}
private const int RETRY_COUNT_UNTIL_THROW = 50;
private static readonly string _errorRetryCountExceeded =
"Ref retried to Update for " + RETRY_COUNT_UNTIL_THROW +
" times But there is always someone else intervened.";
}
/// <summary>Printable string via provided printer </summary>
public interface IPrintable
{
/// <summary>Print to the provided string builder via the provided printer.</summary>
StringBuilder Print(StringBuilder s, Func<StringBuilder, object, StringBuilder> printer);
}
/// <summary>Produces good enough hash codes for the fields</summary>
public static class Hasher
{
/// <summary>Combines hashes of two fields</summary>
public static int Combine<T1, T2>(T1 a, T2 b) =>
Combine(a?.GetHashCode() ?? 0, b?.GetHashCode() ?? 0);
/// <summary>Inspired by System.Tuple.CombineHashCodes</summary>
public static int Combine(int h1, int h2)
{
if (h1 == 0) return h2;
unchecked
{
return (h1 << 5) + h1 ^ h2;
}
}
}
/// <summary>Immutable Key-Value pair. It is reference type (could be check for null),
/// which is different from System value type <see cref="KeyValuePair{TKey,TValue}"/>.
/// In addition provides <see cref="Equals"/> and <see cref="GetHashCode"/> implementations.</summary>
/// <typeparam name="K">Type of Key.</typeparam><typeparam name="V">Type of Value.</typeparam>
public class KV<K, V> : IPrintable
{
/// <summary>Key.</summary>
public readonly K Key;
/// <summary>Value.</summary>
public readonly V Value;
/// <summary>Creates Key-Value object by providing key and value. Does Not check either one for null.</summary>
/// <param name="key">key.</param><param name="value">value.</param>
public KV(K key, V value)
{
Key = key;
Value = value;
}
/// <inheritdoc />
public StringBuilder Print(StringBuilder s, Func<StringBuilder, object, StringBuilder> printer) =>
s.Append("(").To(b => Key == null ? b : printer(b, Key))
.Append(", ").To(b => Value == null ? b : printer(b, Value))
.Append(')');
/// <summary>Creates nice string view.</summary><returns>String representation.</returns>
public override string ToString() =>
Print(new StringBuilder(), (s, x) => s.Append(x)).ToString();
/// <summary>Returns true if both key and value are equal to corresponding key-value of other object.</summary>
public override bool Equals(object obj)
{
var other = obj as KV<K, V>;
return other != null
&& (ReferenceEquals(other.Key, Key) || Equals(other.Key, Key))
&& (ReferenceEquals(other.Value, Value) || Equals(other.Value, Value));
}
/// <summary>Combines key and value hash code</summary>
public override int GetHashCode() => Hasher.Combine(Key, Value);
}
/// <summary>Helpers for <see cref="KV{K,V}"/>.</summary>
public static class KV
{
/// <summary>Creates the key value pair.</summary>
/// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam>
/// <param name="key">Key</param> <param name="value">Value</param> <returns>New pair.</returns>
public static KV<K, V> Of<K, V>(K key, V value) => new KV<K, V>(key, value);
/// <summary>Creates the new pair with new key and old value.</summary>
/// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam>
/// <param name="source">Source value</param> <param name="key">New key</param> <returns>New pair</returns>
public static KV<K, V> WithKey<K, V>(this KV<K, V> source, K key) => new KV<K, V>(key, source.Value);
/// <summary>Creates the new pair with old key and new value.</summary>
/// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam>
/// <param name="source">Source value</param> <param name="value">New value.</param> <returns>New pair</returns>
public static KV<K, V> WithValue<K, V>(this KV<K, V> source, V value) => new KV<K, V>(source.Key, value);
}
/// <summary>Simple helper for creation of the pair of two parts.</summary>
public static class KeyValuePair
{
/// <summary>Pairs key with value.</summary>
public static KeyValuePair<K, V> Pair<K, V>(this K key, V value) =>
new KeyValuePair<K, V>(key, value);
}
/// <summary>Helper structure which allows to distinguish null value from the default value for optional parameter.</summary>
public struct Opt<T>
{
/// <summary>Allows to transparently convert parameter argument to opt structure.</summary>
public static implicit operator Opt<T>(T value) => new Opt<T>(value);
/// <summary>Argument value.</summary>
public readonly T Value;
/// <summary>Indicates that value is provided.</summary>
public readonly bool HasValue;
/// <summary>Wraps passed value in structure. Sets the flag that value is present.</summary>
public Opt(T value)
{
HasValue = true;
Value = value;
}
/// <summary>Helper to get value or default value if value is not present.</summary>
public T OrDefault(T defaultValue = default(T)) => HasValue ? Value : defaultValue;
}
/// <summary>Immutable list - simplest linked list with Head and Rest.</summary>
/// <typeparam name="T">Type of the item.</typeparam>
public sealed class ImList<T>
{
/// <summary>Empty list to Push to.</summary>
public static readonly ImList<T> Empty = new ImList<T>();
/// <summary>True for empty list.</summary>
public bool IsEmpty => Tail == null;
/// <summary>First value in a list.</summary>
public readonly T Head;
/// <summary>The rest of values or Empty if list has a single value.</summary>
public readonly ImList<T> Tail;
/// <summary>Prepends new value and returns new list.</summary>
/// <param name="head">New first value.</param>
/// <returns>List with the new head.</returns>
public ImList<T> Prep(T head) => new ImList<T>(head, this);
/// <summary>Enumerates the list.</summary>
/// <returns>Each item in turn.</returns>
public IEnumerable<T> Enumerate()
{
if (IsEmpty)
yield break;
for (var list = this; !list.IsEmpty; list = list.Tail)
yield return list.Head;
}
#region Implementation
private ImList()
{
}
private ImList(T head, ImList<T> tail)
{
Head = head;
Tail = tail;
}
#endregion
}
/// <summary>Extension methods providing basic operations on a list.</summary>
public static class ImList
{
/// <summary>This a basically a Fold function, to address needs in Map, Filter, Reduce.</summary>
/// <typeparam name="T">Type of list item.</typeparam>
/// <typeparam name="R">Type of result.</typeparam>
/// <param name="source">List to fold.</param>
/// <param name="initialValue">From were to start.</param>
/// <param name="collect">Collects list item into result</param>
/// <returns>Return result or <paramref name="initialValue"/> for empty list.</returns>
public static R To<T, R>(this ImList<T> source, R initialValue, Func<T, R, R> collect)
{
if (source.IsEmpty)
return initialValue;
var value = initialValue;
for (; !source.IsEmpty; source = source.Tail)
value = collect(source.Head, value);
return value;
}
/// <summary>Form of fold function with element index for convenience.</summary>
/// <typeparam name="T">Type of list item.</typeparam>
/// <typeparam name="R">Type of result.</typeparam>
/// <param name="source">List to fold.</param>
/// <param name="initialValue">From were to start.</param>
/// <param name="collect">Collects list item into result</param>
/// <returns>Return result or <paramref name="initialValue"/> for empty list.</returns>
public static R To<T, R>(this ImList<T> source, R initialValue, Func<T, int, R, R> collect)
{
if (source.IsEmpty)
return initialValue;
var value = initialValue;
for (var i = 0; !source.IsEmpty; source = source.Tail)
value = collect(source.Head, i++, value);
return value;
}
/// <summary>Returns new list in reverse order.</summary>
/// <typeparam name="T">List item type</typeparam> <param name="source">List to reverse.</param>
/// <returns>New list. If list consist on single element, then the same list.</returns>
public static ImList<T> Reverse<T>(this ImList<T> source)
{
if (source.IsEmpty || source.Tail.IsEmpty)
return source;
return source.To(ImList<T>.Empty, (it, _) => _.Prep(it));
}
/// <summary>Maps the items from the first list to the result list.</summary>
/// <typeparam name="T">source item type.</typeparam>
/// <typeparam name="R">result item type.</typeparam>
/// <param name="source">input list.</param> <param name="map">converter func.</param>
/// <returns>result list.</returns>
public static ImList<R> Map<T, R>(this ImList<T> source, Func<T, R> map)
{
return source.To(ImList<R>.Empty, (it, _) => _.Prep(map(it))).Reverse();
}
/// <summary>Maps the items from the first list to the result list with item index.</summary>
/// <typeparam name="T">source item type.</typeparam>
/// <typeparam name="R">result item type.</typeparam>
/// <param name="source">input list.</param> <param name="map">converter func.</param>
/// <returns>result list.</returns>
public static ImList<R> Map<T, R>(this ImList<T> source, Func<T, int, R> map)
{
return source.To(ImList<R>.Empty, (it, i, _) => _.Prep(map(it, i))).Reverse();
}
/// <summary>Copies list to array.</summary>
public static T[] ToArray<T>(this ImList<T> source) =>
source.IsEmpty ? ArrayTools.Empty<T>() :
source.Tail.IsEmpty ? new[] { source.Head } :
source.Enumerate().ToArray();
}
/// Given the old value should and the new value should return result updated value.
public delegate V Update<V>(V oldValue, V newValue);
/// Update handler including the key
public delegate V Update<K, V>(K key, V oldValue, V newValue);
/// <summary>Immutable http://en.wikipedia.org/wiki/AVL_tree with integer keys and <typeparamref name="V"/> values.</summary>
public sealed class ImMap<V>
{
/// <summary>Empty tree to start with.</summary>
public static readonly ImMap<V> Empty = new ImMap<V>();
/// <summary>Key.</summary>
public readonly int Key;
/// <summary>Value.</summary>
public readonly V Value;
/// <summary>Left sub-tree/branch, or empty.</summary>
public readonly ImMap<V> Left;
/// <summary>Right sub-tree/branch, or empty.</summary>
public readonly ImMap<V> Right;
/// <summary>Height of longest sub-tree/branch plus 1. It is 0 for empty tree, and 1 for single node tree.</summary>
public readonly int Height;
/// <summary>Returns true is tree is empty.</summary>
public bool IsEmpty => Height == 0;
/// Returns a new tree with added or updated value for specified key.