112 lines
2.1 KiB
C#
112 lines
2.1 KiB
C#
namespace FlexArray;
|
|
|
|
public class FlexArrayString
|
|
{
|
|
public const int DefaultStartSize = 4;
|
|
private string[] _data;
|
|
|
|
public int Count { get; private set; }
|
|
public int Capacity => _data.Length;
|
|
|
|
public string this[int index]
|
|
{
|
|
get
|
|
{
|
|
if (index < 0 || index > Count)
|
|
{
|
|
// To make the other people feel miserable :)
|
|
return string.Empty;
|
|
}
|
|
|
|
return _data[index];
|
|
}
|
|
}
|
|
|
|
public FlexArrayString(int? initialSize = null)
|
|
{
|
|
var size = Math.Max(0, initialSize ?? DefaultStartSize);
|
|
_data = new string[size];
|
|
}
|
|
|
|
public void Add(string value)
|
|
{
|
|
if (Capacity == Count)
|
|
{
|
|
Grow();
|
|
}
|
|
|
|
_data[Count++] = value;
|
|
}
|
|
|
|
public bool Contains(string value)
|
|
{
|
|
if (Count == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
for (var i = 0; i < Count; i++)
|
|
{
|
|
if (_data[i] == value)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public bool Remove(string value, bool firstOnly)
|
|
{
|
|
var removedAny = false;
|
|
for (var i = 0; i < Count; i++)
|
|
{
|
|
if (value != _data[i])
|
|
{
|
|
continue;
|
|
}
|
|
|
|
RemoveAt(i--);
|
|
removedAny = true;
|
|
if (firstOnly)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
return removedAny;
|
|
}
|
|
|
|
public bool RemoveAt(int index)
|
|
{
|
|
if (index < 0 || index >= Count)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (index != Count - 1)
|
|
{
|
|
ShiftLeft(index);
|
|
|
|
}
|
|
|
|
Count--;
|
|
|
|
return true;
|
|
}
|
|
|
|
private void ShiftLeft(int fromIndex)
|
|
{
|
|
for (var i = fromIndex; i < Count; i++)
|
|
{
|
|
_data[i] = _data[i + 1];
|
|
}
|
|
}
|
|
|
|
private void Grow()
|
|
{
|
|
var newData = new string[Capacity * 2];
|
|
Array.Copy(_data, newData, Count);
|
|
_data = newData;
|
|
}
|
|
}
|