PIbd-22_Fedorenko_G.Y._Hydr.../Hydroplane/SetGeneric.cs

77 lines
2.0 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
2023-12-05 19:12:45 +04:00
using Hydroplane.Exceptions;
namespace Hydroplane.Generics
{
2023-10-25 02:19:13 +04:00
internal class SetGeneric<T> where T : class
{
2023-10-25 10:59:54 +04:00
private readonly List<T?> _places;
public int Count => _places.Count;
2023-10-25 02:19:13 +04:00
2023-10-25 10:59:54 +04:00
private readonly int _maxCount;
2023-10-25 02:19:13 +04:00
public SetGeneric(int count)
{
2023-10-25 10:59:54 +04:00
_maxCount = count;
_places = new List<T?>(_maxCount);
}
2023-10-25 02:19:13 +04:00
2023-10-25 10:59:54 +04:00
public bool Insert(T plane)
{
2023-10-25 09:11:32 +04:00
return Insert(plane, 0);
}
2023-10-25 10:59:54 +04:00
public bool Insert(T plane, int position)
{
2023-10-25 10:59:54 +04:00
if (position < 0 || position >= _maxCount)
2023-12-05 19:12:45 +04:00
throw new StorageOverflowException("Impossible to insert");
2023-10-25 09:11:32 +04:00
2023-10-25 10:59:54 +04:00
if (Count >= _maxCount)
2023-12-05 19:12:45 +04:00
throw new StorageOverflowException(_maxCount);
2023-10-25 10:59:54 +04:00
_places.Insert(0, plane);
return true;
}
2023-10-25 10:59:54 +04:00
public bool Remove(int position)
{
2023-12-05 19:12:45 +04:00
if (position >= Count || position < 0)
throw new PlaneNotFoundException("Invalid operation");
if (_places[position] == null)
throw new PlaneNotFoundException(position);
2023-10-25 10:59:54 +04:00
_places.RemoveAt(position);
return true;
}
2023-10-25 10:59:54 +04:00
public T? this[int position]
{
2023-10-25 10:59:54 +04:00
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
public IEnumerable<T?> GetPlanes(int? maxPlanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxPlanes.HasValue && i == maxPlanes.Value)
{
yield break;
}
}
}
}
}