ExpandableArray<TItem>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Stashbox.Utils.Data
{
internal class ExpandableArray<TItem> : IEnumerable<TItem>, IEnumerable
{
private const int InitialSize = 8;
public int Length;
protected TItem[] Repository;
public TItem this[int i] {
get {
return Repository[i];
}
}
public static ExpandableArray<TItem> FromEnumerable(IEnumerable<TItem> initial)
{
return new ExpandableArray<TItem>(initial);
}
public ExpandableArray()
{
}
public ExpandableArray(ExpandableArray<TItem> initial)
{
Repository = initial.AsArray();
Length = Repository.Length;
}
public ExpandableArray(IEnumerable<TItem> initial)
: this(EnumerableExtensions.CastToArray<TItem>(initial))
{
}
public ExpandableArray(TItem[] initial)
{
Repository = initial;
Length = Repository.Length;
}
public void Add(TItem item)
{
int num = EnsureSize(1);
Repository[num] = item;
}
public void AddOrKeep(TItem item)
{
if (!ContainsReference(item)) {
int num = EnsureSize(1);
Repository[num] = item;
}
}
public void AddRange(IEnumerable<TItem> items)
{
AddRange(EnumerableExtensions.CastToArray<TItem>(items));
}
public void AddRange(TItem[] items)
{
int destinationIndex = EnsureSize(items.Length);
Array.Copy(items, 0, Repository, destinationIndex, items.Length);
}
public TItem[] AsArray()
{
if (Length == 0)
return Constants.EmptyArray<TItem>();
Array.Resize<TItem>(ref Repository, Length);
return Repository;
}
public int IndexOf(TItem element)
{
int length = Length;
if (length == 1) {
if ((object)Repository[0] != (object)element)
return -1;
return 0;
}
for (int i = 0; i < length; i++) {
if ((object)Repository[i] == (object)element)
return i;
}
return -1;
}
public bool ContainsReference(TItem element)
{
int length = Length;
if (length == 1)
return (object)Repository[0] == (object)element;
for (int i = 0; i < length; i++) {
if ((object)Repository[i] == (object)element)
return true;
}
return false;
}
public bool Contains(TItem element)
{
int length = Length;
if (length == 1)
return object.Equals(Repository[0], element);
for (int i = 0; i < length; i++) {
if (object.Equals(Repository[i], element))
return true;
}
return false;
}
protected int EnsureSize(int increaseAmount = 1)
{
if (Length == 0)
Repository = new TItem[(increaseAmount > 8) ? increaseAmount : 8];
Length += increaseAmount;
if (Repository.Length >= Length)
return Length - increaseAmount;
int num = Repository.Length * 2;
int newSize = (Length > num) ? Length : num;
Array.Resize<TItem>(ref Repository, newSize);
return Length - increaseAmount;
}
public TItem First()
{
return Repository[0];
}
public IEnumerator<TItem> GetEnumerator()
{
int length = this.Length;
for (int i = 0; i < length; i++) {
yield return this.Repository[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}