Example #1
0
        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
            {
                return(new ArraySegment <T>(buffer.Array, buffer.Offset, count));
            }
        }
Example #2
0
        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));
            }
        }