-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCollectionExtensionsEx.cs
More file actions
100 lines (94 loc) · 2.9 KB
/
Copy pathCollectionExtensionsEx.cs
File metadata and controls
100 lines (94 loc) · 2.9 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
#if NET8_0_OR_GREATER
#define HAS_LISTSPANMETHODS
#endif
#if NET7_0_OR_GREATER
#define HAS_ASREADONLY
#endif
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
#if !HAS_LISTSPANMETHODS
using System.Runtime.InteropServices;
#endif
namespace System.Collections.Generic
{
[SuppressMessage("Design", "CA1002:Do not expose generic lists",
Justification = "Replicating existing APIs")]
public static class CollectionExtensionsEx
{
public static void AddRange<T>(
#if !HAS_LISTSPANMETHODS
this
#endif
List<T> list, params ReadOnlySpan<T> source
)
{
#if HAS_LISTSPANMETHODS
list.AddRange(source);
#else
ThrowHelper.ThrowIfArgumentNull(list, ExceptionArgument.list);
if (source.IsEmpty)
{
return;
}
var currentCount = list.Count;
CollectionsMarshal.SetCount(list, currentCount + source.Length);
source.CopyTo(CollectionsMarshal.AsSpan(list).Slice(currentCount + 1));
#endif
}
public static void InsertRange<T>(
#if !HAS_LISTSPANMETHODS
this
#endif
List<T> list, int index, params ReadOnlySpan<T> source
)
{
#if HAS_LISTSPANMETHODS
list.InsertRange(index, source);
#else
ThrowHelper.ThrowIfArgumentNull(list, ExceptionArgument.list);
if ((uint)index > (uint)list.Count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
if (source.IsEmpty)
{
return;
}
var currentCount = list.Count;
CollectionsMarshal.SetCount(list, currentCount + source.Length);
var items = CollectionsMarshal.AsSpan(list);
if (index < currentCount)
{
items.Slice(index, currentCount - index).CopyTo(items.Slice(index + source.Length));
}
source.CopyTo(items.Slice(index));
#endif
}
public static void CopyTo<T>(
#if !HAS_LISTSPANMETHODS
this
#endif
List<T> list, Span<T> destination
)
{
#if HAS_LISTSPANMETHODS
list.CopyTo(destination);
#else
ThrowHelper.ThrowIfArgumentNull(list, ExceptionArgument.list);
CollectionsMarshal.AsSpan(list).CopyTo(destination);
#endif
}
public static ReadOnlyCollection<T> AsReadOnly<T>(
#if !HAS_ASREADONLY
this
#endif
IList<T> list
) => new(list);
public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(
#if !HAS_ASREADONLY
this
#endif
IDictionary<TKey, TValue> list
) where TKey : notnull => new(list);
}
}