三国卡牌客户端基础资源仓库
yyl
2025-05-15 aac116baba3b0c43808e05458c2d4793a0729730
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
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
 
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
 
namespace Cysharp.Threading.Tasks.Internal
{
    internal static class ArrayUtil
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void EnsureCapacity<T>(ref T[] array, int index)
        {
            if (array.Length <= index)
            {
                EnsureCore(ref array, index);
            }
        }
 
        // rare case, no inlining.
        [MethodImpl(MethodImplOptions.NoInlining)]
        static void EnsureCore<T>(ref T[] array, int index)
        {
            var newSize = array.Length * 2;
            var newArray = new T[(index < newSize) ? newSize : (index * 2)];
            Array.Copy(array, 0, newArray, 0, array.Length);
 
            array = newArray;
        }
 
        /// <summary>
        /// Optimizing utility to avoid .ToArray() that creates buffer copy(cut to just size).
        /// </summary>
        public static (T[] array, int length) Materialize<T>(IEnumerable<T> source)
        {
            if (source is T[] array)
            {
                return (array, array.Length);
            }
 
            var defaultCount = 4;
            if (source is ICollection<T> coll)
            {
                defaultCount = coll.Count;
                var buffer = new T[defaultCount];
                coll.CopyTo(buffer, 0);
                return (buffer, defaultCount);
            }
            else if (source is IReadOnlyCollection<T> rcoll)
            {
                defaultCount = rcoll.Count;
            }
 
            if (defaultCount == 0)
            {
                return (Array.Empty<T>(), 0);
            }
 
            {
                var index = 0;
                var buffer = new T[defaultCount];
                foreach (var item in source)
                {
                    EnsureCapacity(ref buffer, index);
                    buffer[index++] = item;
                }
 
                return (buffer, index);
            }
        }
    }
}