-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtil.cs
More file actions
1004 lines (828 loc) · 33.2 KB
/
Copy pathUtil.cs
File metadata and controls
1004 lines (828 loc) · 33.2 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
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using ICSharpCode.Decompiler;
using ICSharpCode.NRefactory.CSharp;
using JSIL.Ast;
using Mono.Cecil;
using TypeInfo = JSIL.Internal.TypeInfo;
namespace JSIL.Internal {
public enum EscapingMode {
None,
MemberIdentifier,
TypeIdentifier,
String
}
public static class Util {
public static readonly HashSet<string> ReservedWords = new HashSet<string> {
"break", "do", "instanceof", "typeof",
"case", "else", "new", "var",
"catch", "finally", "return", "void",
"continue", "for", "switch", "while",
"debugger", "function", "this", "with",
"default", "if", "throw", "delete",
"in", "try", "import", "class", "enum",
"export", "extends", "super", "let",
"package", "interface", "implements", "private",
"protected", "public", "static", "yield",
"const", "true", "false", "null", "arguments",
"eval"
};
// We need to flag these names as reserved because they are properties of
// Function in many browsers.
public static readonly HashSet<string> ReservedIdentifiers = new HashSet<string> {
"name", "length", "arity", "constructor",
"caller", "arguments", "call", "apply", "bind"
};
public static Regex ValidIdentifier = new Regex(
"$[A-Za-z_$]([A-Za-z_$0-9]*)^",
RegexOptions.Compiled | RegexOptions.ExplicitCapture
);
private static ThreadLocal<StringBuilder> EscapeStringBuilder = new ThreadLocal<StringBuilder>(
() => new StringBuilder(10240)
);
public static string GetPathOfAssembly (Assembly assembly) {
var uri = new Uri(assembly.CodeBase);
var result = Uri.UnescapeDataString(uri.AbsolutePath);
if (String.IsNullOrWhiteSpace(result))
result = assembly.Location;
result = result.Replace('/', System.IO.Path.DirectorySeparatorChar);
return result;
}
public static string EscapeIdentifier (string identifier, EscapingMode escapingMode = EscapingMode.MemberIdentifier) {
if (escapingMode == EscapingMode.None)
return identifier;
bool isEscaped = false;
string result = identifier;
var sb = EscapeStringBuilder.Value;
sb.Clear();
for (int i = 0, l = identifier.Length; i < l; i++) {
var ch = identifier[i];
switch (ch) {
case '.':
if (escapingMode != EscapingMode.MemberIdentifier)
sb.Append(".");
else {
sb.Append("_");
isEscaped = true;
}
break;
case '/':
if (escapingMode == EscapingMode.MemberIdentifier) {
sb.Append("_");
isEscaped = true;
} else if (escapingMode == EscapingMode.TypeIdentifier) {
sb.Append("_");
isEscaped = true;
} else
sb.Append("/");
break;
case '+':
if (escapingMode == EscapingMode.MemberIdentifier) {
sb.Append("_");
isEscaped = true;
} else if (escapingMode == EscapingMode.TypeIdentifier) {
sb.Append("_");
isEscaped = true;
} else
sb.Append("+");
break;
case '`':
if (escapingMode != EscapingMode.String) {
sb.Append("$b");
} else {
sb.Append("`");
}
isEscaped = true;
break;
case '~':
sb.Append("$t");
isEscaped = true;
break;
case ':':
sb.Append("$co");
isEscaped = true;
break;
case '<':
sb.Append("$l");
isEscaped = true;
break;
case '>':
sb.Append("$g");
isEscaped = true;
break;
case '(':
sb.Append("$lp");
isEscaped = true;
break;
case ')':
sb.Append("$rp");
isEscaped = true;
break;
case '{':
sb.Append("$lc");
isEscaped = true;
break;
case '}':
sb.Append("$rc");
isEscaped = true;
break;
case '[':
sb.Append("$lb");
isEscaped = true;
break;
case ']':
sb.Append("$rb");
isEscaped = true;
break;
case '@':
sb.Append("$at");
isEscaped = true;
break;
case '-':
sb.Append("$da");
isEscaped = true;
break;
case '=':
sb.Append("$eq");
isEscaped = true;
break;
case ' ':
sb.Append("$sp");
isEscaped = true;
break;
case '?':
sb.Append("$qu");
isEscaped = true;
break;
case '!':
sb.Append("$ex");
isEscaped = true;
break;
case '*':
sb.Append("$as");
isEscaped = true;
break;
case '&':
sb.Append("$am");
isEscaped = true;
break;
case ',':
sb.Append("$cm");
isEscaped = true;
break;
case '|':
sb.Append("$vb");
isEscaped = true;
break;
case '\'':
sb.Append("$q");
isEscaped = true;
break;
default:
if ((ch <= 32) || (ch >= 127)) {
sb.AppendFormat("${0:x}", (int)ch);
isEscaped = true;
} else
sb.Append(ch);
break;
}
}
if (isEscaped)
result = sb.ToString();
bool isReservedWord = ReservedWords.Contains(result);
if (isReservedWord)
result = "$" + result;
return result;
}
public static string EscapeCharacter (char character, bool forJson) {
switch (character) {
case '\'':
return @"\'";
case '\\':
return @"\\";
case '"':
return "\\\"";
case '\t':
return @"\t";
case '\r':
return @"\r";
case '\n':
return @"\n";
default: {
if (forJson || (character > 255))
return String.Format(@"\u{0:x4}", (int)character);
else
return String.Format(@"\x{0:x2}", (int)character);
}
}
}
public static string EscapeString (string text, char quoteCharacter = '\"', bool forJson = false) {
if (text == null)
return "null";
var sb = EscapeStringBuilder.Value;
sb.Clear();
sb.Append(quoteCharacter);
foreach (var ch in text) {
if (ch == quoteCharacter)
sb.Append(EscapeCharacter(ch, forJson));
else if (ch == '\\')
sb.Append(@"\\");
else if ((ch < ' ') || (ch > 127))
sb.Append(EscapeCharacter(ch, forJson));
else
sb.Append(ch);
}
sb.Append(quoteCharacter);
return sb.ToString();
}
public static string DemangleCecilTypeName (string typeName) {
return typeName.Replace("/", "+");
}
public sealed class ListSkipAdapter<T> : IList<T> {
public readonly IList<T> List;
public readonly int Offset;
public ListSkipAdapter (IList<T> list, int offset) {
List = list;
Offset = offset;
}
public int IndexOf (T item) {
throw new NotImplementedException("ListSkipAdapter.IndexOf not implemented");
}
public void Insert (int index, T item) {
List.Insert(index + Offset, item);
}
public void RemoveAt (int index) {
List.RemoveAt(index + Offset);
}
public T this[int index] {
get {
return List[index + Offset];
}
set {
List[index + Offset] = value;
}
}
public void Add (T item) {
List.Add(item);
}
public void Clear () {
throw new NotImplementedException("ListSkipAdapter.Clear not implemented");
}
public bool Contains (T item) {
throw new NotImplementedException("ListSkipAdapter.Contains not implemented");
}
public void CopyTo (T[] array, int arrayIndex) {
for (int i = 0, c = Count; i < c; i++)
array[i + arrayIndex] = List[i + Offset];
}
public int Count {
get { return List.Count - Offset; }
}
public bool IsReadOnly {
get { return List.IsReadOnly; }
}
public bool Remove (T item) {
throw new NotImplementedException("ListSkipAdapter.Remove not implemented");
}
public IEnumerator<T> GetEnumerator () {
return (List as IEnumerable<T>).Skip(Offset).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {
return (List as IEnumerable<T>).Skip(Offset).GetEnumerator();
}
}
public static IList<T> Skip<T> (this IList<T> list, int offset) {
return new ListSkipAdapter<T>(list, offset);
}
public static string Indent (object inner) {
if (inner == null)
return "";
var text = inner.ToString();
return String.Join(
Environment.NewLine,
(from l in text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
select " " + l).ToArray()
);
}
}
public class ConcurrentHashQueue<TValue> {
protected readonly ConcurrentDictionary<TValue, int> Counts;
protected readonly ConcurrentQueue<TValue> Queue;
public ConcurrentHashQueue (IEqualityComparer<TValue> comparer) {
Queue = new ConcurrentQueue<TValue>();
Counts = new ConcurrentDictionary<TValue, int>(comparer);
}
public ConcurrentHashQueue (int concurrencyLevel, int capacity, IEqualityComparer<TValue> comparer) {
Queue = new ConcurrentQueue<TValue>();
Counts = new ConcurrentDictionary<TValue, int>(concurrencyLevel, capacity, comparer);
}
public void Clear () {
Counts.Clear();
TValue temp;
while (Queue.Count > 0)
Queue.TryDequeue(out temp);
}
public bool TryEnqueue (TValue value) {
if (Counts.TryAdd(value, 1)) {
Queue.Enqueue(value);
return true;
} else {
int existingCount;
int tryCount = 10;
while (Counts.TryGetValue(value, out existingCount)) {
var newCount = existingCount + 1;
if (Counts.TryUpdate(value, newCount, existingCount))
return true;
// Abort after a few tries.
if ((tryCount--) <= 0)
return false;
}
}
return false;
}
public bool TryDequeue (out TValue value) {
if (Queue.TryDequeue(out value)) {
int existingCount;
int tryCount = 10;
while (Counts.TryGetValue(value, out existingCount)) {
int newCount = existingCount - 1;
if (newCount <= 0) {
if (Counts.TryRemove(value, out existingCount))
return true;
} else {
if (Counts.TryUpdate(value, existingCount, newCount))
return true;
}
// Abort after a few tries.
if ((tryCount--) <= 0)
return false;
}
}
return false;
}
public int Count {
get {
return Queue.Count;
}
}
public IEnumerable<TValue> TryDequeueAll {
get {
TValue value;
while (TryDequeue(out value))
yield return value;
}
}
}
public class ConcurrentCache<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IDisposable {
public delegate TValue CreatorFunction (TKey key);
public delegate TValue CreatorFunction<in TUserData> (TKey key, TUserData userData);
protected class ConstructionState : IDisposable {
private volatile bool IsDisposed;
private int WaiterCount = 0, DisposePending = 0;
private readonly ManualResetEventSlim Signal = new ManualResetEventSlim(false);
public readonly Thread ConstructingThread = Thread.CurrentThread;
public bool Wait () {
if (ConstructingThread == Thread.CurrentThread)
throw new InvalidOperationException("Recursive construction of cache entry");
try {
Interlocked.Increment(ref WaiterCount);
if (IsDisposed)
return true;
Signal.Wait();
return true;
} catch (ObjectDisposedException) {
return false;
} finally {
var newCount = Interlocked.Decrement(ref WaiterCount);
if (newCount <= 0) {
if (Interlocked.CompareExchange(ref DisposePending, 0, 1) == 1) {
IsDisposed = true;
Thread.MemoryBarrier();
Signal.Dispose();
}
}
}
}
public void Set () {
try {
if (!IsDisposed)
Signal.Set();
} catch (ObjectDisposedException) {
// Threading is hard and I'm lazy.
}
}
public void Dispose () {
if (Interlocked.Exchange(ref DisposePending, 1) == 0) {
if (WaiterCount <= 0) {
DisposePending = 0;
IsDisposed = true;
Thread.MemoryBarrier();
Signal.Dispose();
}
}
}
}
protected readonly ConcurrentDictionary<TKey, TValue> Storage;
protected readonly ConcurrentDictionary<TKey, ConstructionState> States;
protected readonly IEqualityComparer<TKey> Comparer;
public ConcurrentCache () {
Comparer = EqualityComparer<TKey>.Default;
Storage = new ConcurrentDictionary<TKey, TValue>();
States = new ConcurrentDictionary<TKey, ConstructionState>();
}
public ConcurrentCache (IEqualityComparer<TKey> comparer) {
Comparer = comparer;
Storage = new ConcurrentDictionary<TKey, TValue>(comparer);
States = new ConcurrentDictionary<TKey, ConstructionState>(comparer);
}
public ConcurrentCache (int concurrencyLevel, int capacity) {
Comparer = EqualityComparer<TKey>.Default;
Storage = new ConcurrentDictionary<TKey, TValue>(concurrencyLevel, capacity);
States = new ConcurrentDictionary<TKey, ConstructionState>(concurrencyLevel, concurrencyLevel);
}
public ConcurrentCache (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer) {
Comparer = comparer;
Storage = new ConcurrentDictionary<TKey, TValue>(concurrencyLevel, capacity, comparer);
States = new ConcurrentDictionary<TKey, ConstructionState>(concurrencyLevel, concurrencyLevel, comparer);
}
protected ConcurrentCache (ConcurrentCache<TKey, TValue> cloneSource) {
// FIXME: Probably not thread-safe?
Storage = new ConcurrentDictionary<TKey, TValue>(cloneSource.Storage, cloneSource.Comparer);
States = new ConcurrentDictionary<TKey, ConstructionState>(Environment.ProcessorCount, Environment.ProcessorCount, cloneSource.Comparer);
}
public ConcurrentCache<TKey, TValue> Clone () {
return new ConcurrentCache<TKey, TValue>(this);
}
public int Count {
get {
return Storage.Count + States.Count;
}
}
public virtual void Dispose () {
Clear();
}
public void Clear () {
Storage.Clear();
foreach (var kvp in States)
kvp.Value.Dispose();
States.Clear();
}
public IEnumerable<TKey> Keys {
get {
return Storage.Keys;
}
}
public bool MightContainKey (TKey key) {
return Storage.ContainsKey(key) || States.ContainsKey(key);
}
public bool ContainsKey (TKey key) {
return Storage.ContainsKey(key);
}
public bool TryGet (TKey key, out TValue result) {
ConstructionState state;
while (States.TryGetValue(key, out state)) {
if (!state.Wait()) {
result = default(TValue);
return false;
}
}
return Storage.TryGetValue(key, out result);
}
private bool TryCreateSetup (TKey key, out ConstructionState state) {
if (Storage.ContainsKey(key)) {
state = null;
return false;
}
state = new ConstructionState();
if (States.TryAdd(key, state)) {
if (Storage.ContainsKey(key)) {
TryCreateTeardown(key, state);
return false;
}
return true;
} else {
state.Dispose();
return false;
}
}
private void TryCreateTeardown (TKey key, ConstructionState state) {
if (States.TryRemove(key, out state)) {
state.Set();
state.Dispose();
}
}
public bool TryCreate (TKey key, CreatorFunction creator) {
ConstructionState state;
if (TryCreateSetup(key, out state)) {
try {
var result = creator(key);
if (!Storage.TryAdd(key, result))
throw new InvalidOperationException("Cache entry was created by someone else while construction lock was held");
return true;
} finally {
TryCreateTeardown(key, state);
}
}
return false;
}
public bool TryCreate<TUserData> (TKey key, TUserData userData, CreatorFunction<TUserData> creator, Predicate<TValue> shouldAdd = null) {
ConstructionState state;
if (TryCreateSetup(key, out state)) {
try {
var result = creator(key, userData);
if ((shouldAdd == null) || shouldAdd(result)) {
if (!Storage.TryAdd(key, result))
throw new InvalidOperationException("Cache entry was created by someone else while construction lock was held");
return true;
} else {
return false;
}
} finally {
TryCreateTeardown(key, state);
}
}
return false;
}
private bool TryWaitForConstruction (TKey key) {
ConstructionState state;
bool waitFailed = false;
while (States.TryGetValue(key, out state))
waitFailed = !state.Wait();
return waitFailed;
}
public TValue GetOrCreate (TKey key, CreatorFunction creator) {
while (true) {
bool waitFailed = TryWaitForConstruction(key);
TValue result;
if (Storage.TryGetValue(key, out result))
return result;
else if (waitFailed)
throw new ObjectDisposedException("Cache", "The cache was cleared or disposed.");
TryCreate(key, creator);
}
}
public TValue GetOrCreate<TUserData> (TKey key, TUserData userData, CreatorFunction<TUserData> creator) {
bool createSuccess = false;
while (true) {
bool waitFailed = TryWaitForConstruction(key);
TValue result;
if (Storage.TryGetValue(key, out result))
return result;
else if (waitFailed)
throw new ObjectDisposedException("Cache", "The cache was cleared or disposed.");
else if (createSuccess)
throw new ThreadStateException("Failed to retrieve cache element after creating it");
createSuccess |= TryCreate(key, userData, creator);
}
}
public bool TryRemove (TKey key) {
ConstructionState state;
while (States.TryGetValue(key, out state)) {
if (!state.Wait())
return false;
}
TValue temp;
return Storage.TryRemove(key, out temp);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator () {
return Storage.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {
return Storage.GetEnumerator();
}
}
public class ReferenceComparer<T> : IEqualityComparer<T>
where T : class {
public bool Equals (T x, T y) {
return x == y;
}
public int GetHashCode (T obj) {
return obj.GetHashCode();
}
}
public static class TemporaryVariable {
public static JSTemporaryVariable ForFunction (
JSFunctionExpression function, TypeReference type,
IFunctionSource functionSource
) {
var index = function.TemporaryVariableTypes.Count;
function.TemporaryVariableTypes.Add(type);
MethodReference methodRef = null;
if (function.Method != null)
methodRef = function.Method.Reference;
var id = string.Format("$temp{0:X2}", index);
var result = new JSTemporaryVariable(id, type, methodRef);
function.AllVariables.Add(id, result);
// HACK: If the static analysis data for the function is stale, this temporary
// variable might get eliminated later despite being in use.
// We should really just fix all the transforms that aren't invalidating static
// analysis data when they should, but this is good enough for now.
if (function.Method != null)
functionSource.InvalidateFirstPass(function.Method.QualifiedIdentifier);
return result;
}
}
public struct HashedString {
public readonly int HashCode;
public readonly string String;
public HashedString (string str) {
String = str;
HashCode = str.GetHashCode();
}
public HashedString (string str, int hashCode) {
String = str;
HashCode = hashCode;
}
}
public class HashedStringComparer : IEqualityComparer<HashedString> {
public bool Equals (HashedString x, HashedString y) {
return String.Equals(x.String, y.String, StringComparison.Ordinal);
}
public int GetHashCode (HashedString obj) {
return obj.HashCode;
}
}
public static class ImmutableArrayPool<T> {
private class State {
public readonly T[] Buffer;
public int ElementsUsed;
public State (int capacity) {
Buffer = new T[capacity];
ElementsUsed = 0;
}
}
// The large object heap threshold is roughly 85KB so we set our block size small.
// this ensures that our blocks start in gen0 and can get collected early, instead
// of spending their entire life on the large object heap.
// This also reduces waste in cases where some but not all of the buffers expire.
public const int MaxSizeBytes = 1 * 1024;
public static readonly int Capacity;
public static readonly ArraySegment<T> Empty = new ArraySegment<T>(new T[0]);
private readonly static ThreadLocal<State> ThreadLocal = new ThreadLocal<State>();
static ImmutableArrayPool () {
// Assume heap reference
int itemSize = Environment.Is64BitProcess
? 8
: 4;
try {
// If it's a blittable type, estimate its in-memory size
if (!typeof(T).IsClass)
itemSize = Marshal.SizeOf(typeof(T));
} catch {
// Non-blittable struct. Make a rough estimate of size (conservative) so we try to stay below LOH threshold.
itemSize = 32;
}
Capacity = MaxSizeBytes / itemSize;
}
public static ArraySegment<T> Allocate (int count) {
if (count == 0)
return Empty;
if (count > Capacity)
return new ArraySegment<T>(new T[count], 0, count);
var data = ThreadLocal.Value;
bool usedUpElements = false;
bool allocateNew = (data == null) ||
(usedUpElements = (data.ElementsUsed >= Capacity - count));
if (allocateNew) {
data = ThreadLocal.Value = new State(Capacity);
usedUpElements = false;
}
if (usedUpElements)
data.ElementsUsed = 0;
var offset = data.ElementsUsed;
data.ElementsUsed += count;
return new ArraySegment<T>(data.Buffer, offset, count);
}
public static ArraySegment<T> Elements (T a) {
var result = Allocate(1);
result.Array[result.Offset + 0] = a;
return result;
}
public static ArraySegment<T> Elements (T a, T b) {
var result = Allocate(2);
result.Array[result.Offset + 0] = a;
result.Array[result.Offset + 1] = b;
return result;
}
public static ArraySegment<T> Elements (T a, T b, T c) {
var result = Allocate(3);
result.Array[result.Offset + 0] = a;
result.Array[result.Offset + 1] = b;
result.Array[result.Offset + 2] = c;
return result;
}
public static ArraySegment<T> Elements (T a, T b, T c, T d) {
var result = Allocate(4);
result.Array[result.Offset + 0] = a;
result.Array[result.Offset + 1] = b;
result.Array[result.Offset + 2] = c;
result.Array[result.Offset + 3] = d;
return result;
}
}
public static class ImmutableArrayPoolExtensions {
#if TARGETTING_FX_4_5
public static ArraySegment<T> ToEnumerable<T> (this ArraySegment<T> aseg) {
return aseg;
}
#else
public struct ArraySegmentEnumerable<T> : IEnumerable<T> {
public struct Enumerator : IEnumerator<T> {
public readonly ArraySegment<T> ArraySegment;
private int Index;
public Enumerator (ArraySegment<T> aseg) {
ArraySegment = aseg;
Index = -1;
}
public bool MoveNext () {
Index += 1;
return (Index < ArraySegment.Count);
}
public T Current {
get {
return ArraySegment.Array[ArraySegment.Offset + Index];
}
}
public void Reset () {
Index = -1;
}
public void Dispose () {
}
object System.Collections.IEnumerator.Current {
get {
return Current;
}
}
}
public readonly ArraySegment<T> ArraySegment;
public ArraySegmentEnumerable (ArraySegment<T> aseg) {
ArraySegment = aseg;
}
public Enumerator GetEnumerator () {
return new Enumerator(ArraySegment);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator () {
return new Enumerator(ArraySegment);
}
IEnumerator IEnumerable.GetEnumerator () {
return new Enumerator(ArraySegment);
}
}
public static ArraySegmentEnumerable<T> ToEnumerable<T> (this ArraySegment<T> aseg) {
return new ArraySegmentEnumerable<T>(aseg);
}
#endif
public static ArraySegment<T> ToImmutableArray<T> (this IEnumerable<T> enumerable) {
var collection = enumerable as ICollection<T>;
#if TARGETTING_FX_4_5
var readOnlyCollection = enumerable as IReadOnlyCollection<T>;
#endif
var array = enumerable as T[];
if (collection != null) {
var count = collection.Count;
var buffer = ImmutableArrayPool<T>.Allocate(count);
collection.CopyTo(buffer.Array, buffer.Offset);
return buffer;
#if TARGETTING_FX_4_5
} else if (readOnlyCollection != null) {
return ToImmutableArray(enumerable, readOnlyCollection.Count);
#endif
} else if (array != null) {
return new ArraySegment<T>(array);
} else {
// Slow path =[
array = enumerable.ToArray();
return new ArraySegment<T>(array);
}
}
public static ArraySegment<T> ToImmutableArray<T> (this IEnumerable<T> enumerable, int maximumCount) {
int count = maximumCount;
var buffer = ImmutableArrayPool<T>.Allocate(maximumCount);
using (var e = enumerable.GetEnumerator()) {
for (var i = 0; i < count; i++) {
if (!e.MoveNext()) {
count = i;
break;
}
buffer.Array[i + buffer.Offset] = e.Current;
}
if (e.MoveNext())
throw new ArgumentException("Enumerable was longer", "maximumCount");
}
if (buffer.Array == null)
return ImmutableArrayPool<T>.Empty;
else