NadekoBot/NadekoBot.Core/Modules/Permissions/Common/PermissionsCollection.cs

75 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2017-07-17 19:42:36 +00:00
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
2017-07-17 19:42:36 +00:00
namespace NadekoBot.Modules.Permissions.Common
{
2017-07-17 19:42:36 +00:00
public class PermissionsCollection<T> : IndexedCollection<T> where T : class, IIndexed
{
2017-04-06 19:00:46 +00:00
private readonly object _localLocker = new object();
public PermissionsCollection(IEnumerable<T> source) : base(source)
{
}
public static implicit operator List<T>(PermissionsCollection<T> x) =>
x.Source;
2017-04-06 19:00:46 +00:00
public override void Clear()
{
2017-04-06 19:00:46 +00:00
lock (_localLocker)
{
var first = Source[0];
2017-04-06 19:00:46 +00:00
base.Clear();
Source[0] = first;
}
}
2017-04-06 19:00:46 +00:00
public override bool Remove(T item)
{
bool removed;
2017-04-06 19:00:46 +00:00
lock (_localLocker)
{
if(Source.IndexOf(item) == 0)
throw new ArgumentException("You can't remove first permsission (allow all)");
2017-04-06 19:00:46 +00:00
removed = base.Remove(item);
}
return removed;
}
2017-04-06 19:00:46 +00:00
public override void Insert(int index, T item)
{
2017-04-06 19:00:46 +00:00
lock (_localLocker)
{
if(index == 0) // can't insert on first place. Last item is always allow all.
throw new IndexOutOfRangeException(nameof(index));
2017-04-06 19:00:46 +00:00
base.Insert(index, item);
}
}
2017-04-06 19:00:46 +00:00
public override void RemoveAt(int index)
{
2017-04-06 19:00:46 +00:00
lock (_localLocker)
{
if(index == 0) // you can't remove first permission (allow all)
2017-04-06 19:00:46 +00:00
throw new IndexOutOfRangeException(nameof(index));
2017-04-06 19:00:46 +00:00
base.RemoveAt(index);
}
}
2017-04-06 19:00:46 +00:00
public override T this[int index] {
2017-07-17 19:42:36 +00:00
get => Source[index];
set {
2017-04-06 19:00:46 +00:00
lock (_localLocker)
{
if(index == 0) // can't set first element. It's always allow all
throw new IndexOutOfRangeException(nameof(index));
2017-04-06 19:00:46 +00:00
base[index] = value;
}
}
}
}
}