Started converting websocket and rpc classes
This commit is contained in:
74
src/Discord.Net.Core/Utils/AsyncEvent.cs
Normal file
74
src/Discord.Net.Core/Utils/AsyncEvent.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal class AsyncEvent<T>
|
||||
{
|
||||
private readonly object _subLock = new object();
|
||||
internal ImmutableArray<T> _subscriptions;
|
||||
|
||||
public IReadOnlyList<T> Subscriptions => _subscriptions;
|
||||
|
||||
public AsyncEvent()
|
||||
{
|
||||
_subscriptions = ImmutableArray.Create<T>();
|
||||
}
|
||||
|
||||
public void Add(T subscriber)
|
||||
{
|
||||
lock (_subLock)
|
||||
_subscriptions = _subscriptions.Add(subscriber);
|
||||
}
|
||||
public void Remove(T subscriber)
|
||||
{
|
||||
lock (_subLock)
|
||||
_subscriptions = _subscriptions.Remove(subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class EventExtensions
|
||||
{
|
||||
public static async Task InvokeAsync(this AsyncEvent<Func<Task>> eventHandler)
|
||||
{
|
||||
var subscribers = eventHandler.Subscriptions;
|
||||
if (subscribers.Count > 0)
|
||||
{
|
||||
for (int i = 0; i < subscribers.Count; i++)
|
||||
await subscribers[i].Invoke().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
public static async Task InvokeAsync<T>(this AsyncEvent<Func<T, Task>> eventHandler, T arg)
|
||||
{
|
||||
var subscribers = eventHandler.Subscriptions;
|
||||
for (int i = 0; i < subscribers.Count; i++)
|
||||
await subscribers[i].Invoke(arg).ConfigureAwait(false);
|
||||
}
|
||||
public static async Task InvokeAsync<T1, T2>(this AsyncEvent<Func<T1, T2, Task>> eventHandler, T1 arg1, T2 arg2)
|
||||
{
|
||||
var subscribers = eventHandler.Subscriptions;
|
||||
for (int i = 0; i < subscribers.Count; i++)
|
||||
await subscribers[i].Invoke(arg1, arg2).ConfigureAwait(false);
|
||||
}
|
||||
public static async Task InvokeAsync<T1, T2, T3>(this AsyncEvent<Func<T1, T2, T3, Task>> eventHandler, T1 arg1, T2 arg2, T3 arg3)
|
||||
{
|
||||
var subscribers = eventHandler.Subscriptions;
|
||||
for (int i = 0; i < subscribers.Count; i++)
|
||||
await subscribers[i].Invoke(arg1, arg2, arg3).ConfigureAwait(false);
|
||||
}
|
||||
public static async Task InvokeAsync<T1, T2, T3, T4>(this AsyncEvent<Func<T1, T2, T3, T4, Task>> eventHandler, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
|
||||
{
|
||||
var subscribers = eventHandler.Subscriptions;
|
||||
for (int i = 0; i < subscribers.Count; i++)
|
||||
await subscribers[i].Invoke(arg1, arg2, arg3, arg4).ConfigureAwait(false);
|
||||
}
|
||||
public static async Task InvokeAsync<T1, T2, T3, T4, T5>(this AsyncEvent<Func<T1, T2, T3, T4, T5, Task>> eventHandler, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
|
||||
{
|
||||
var subscribers = eventHandler.Subscriptions;
|
||||
for (int i = 0; i < subscribers.Count; i++)
|
||||
await subscribers[i].Invoke(arg1, arg2, arg3, arg4, arg5).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
475
src/Discord.Net.Core/Utils/ConcurrentHashSet.cs
Normal file
475
src/Discord.Net.Core/Utils/ConcurrentHashSet.cs
Normal file
@@ -0,0 +1,475 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
//Based on https://github.com/dotnet/corefx/blob/master/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs
|
||||
//Copyright (c) .NET Foundation and Contributors
|
||||
[DebuggerDisplay("Count = {Count}")]
|
||||
internal class ConcurrentHashSet<T> : IReadOnlyCollection<T>
|
||||
{
|
||||
private sealed class Tables
|
||||
{
|
||||
internal readonly Node[] _buckets;
|
||||
internal readonly object[] _locks;
|
||||
internal volatile int[] _countPerLock;
|
||||
|
||||
internal Tables(Node[] buckets, object[] locks, int[] countPerLock)
|
||||
{
|
||||
_buckets = buckets;
|
||||
_locks = locks;
|
||||
_countPerLock = countPerLock;
|
||||
}
|
||||
}
|
||||
private sealed class Node
|
||||
{
|
||||
internal readonly T _value;
|
||||
internal volatile Node _next;
|
||||
internal readonly int _hashcode;
|
||||
|
||||
internal Node(T key, int hashcode, Node next)
|
||||
{
|
||||
_value = key;
|
||||
_next = next;
|
||||
_hashcode = hashcode;
|
||||
}
|
||||
}
|
||||
|
||||
private const int DefaultCapacity = 31;
|
||||
private const int MaxLockNumber = 1024;
|
||||
|
||||
private static int GetBucket(int hashcode, int bucketCount)
|
||||
{
|
||||
int bucketNo = (hashcode & 0x7fffffff) % bucketCount;
|
||||
return bucketNo;
|
||||
}
|
||||
private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
|
||||
{
|
||||
bucketNo = (hashcode & 0x7fffffff) % bucketCount;
|
||||
lockNo = bucketNo % lockCount;
|
||||
}
|
||||
private static int DefaultConcurrencyLevel => PlatformHelper.ProcessorCount;
|
||||
|
||||
private volatile Tables _tables;
|
||||
private readonly IEqualityComparer<T> _comparer;
|
||||
private readonly bool _growLockArray;
|
||||
private int _budget;
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
int acquiredLocks = 0;
|
||||
try
|
||||
{
|
||||
AcquireAllLocks(ref acquiredLocks);
|
||||
|
||||
for (int i = 0; i < _tables._countPerLock.Length; i++)
|
||||
count += _tables._countPerLock[i];
|
||||
}
|
||||
finally { ReleaseLocks(0, acquiredLocks); }
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
public bool IsEmpty
|
||||
{
|
||||
get
|
||||
{
|
||||
int acquiredLocks = 0;
|
||||
try
|
||||
{
|
||||
// Acquire all locks
|
||||
AcquireAllLocks(ref acquiredLocks);
|
||||
|
||||
for (int i = 0; i < _tables._countPerLock.Length; i++)
|
||||
{
|
||||
if (_tables._countPerLock[i] != 0)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
finally { ReleaseLocks(0, acquiredLocks); }
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public ReadOnlyCollection<T> Values
|
||||
{
|
||||
get
|
||||
{
|
||||
int locksAcquired = 0;
|
||||
try
|
||||
{
|
||||
AcquireAllLocks(ref locksAcquired);
|
||||
List<T> values = new List<T>();
|
||||
|
||||
for (int i = 0; i < _tables._buckets.Length; i++)
|
||||
{
|
||||
Node current = _tables._buckets[i];
|
||||
while (current != null)
|
||||
{
|
||||
values.Add(current._value);
|
||||
current = current._next;
|
||||
}
|
||||
}
|
||||
|
||||
return new ReadOnlyCollection<T>(values);
|
||||
}
|
||||
finally { ReleaseLocks(0, locksAcquired); }
|
||||
}
|
||||
}
|
||||
|
||||
public ConcurrentHashSet()
|
||||
: this(DefaultConcurrencyLevel, DefaultCapacity, true, EqualityComparer<T>.Default) { }
|
||||
public ConcurrentHashSet(int concurrencyLevel, int capacity)
|
||||
: this(concurrencyLevel, capacity, false, EqualityComparer<T>.Default) { }
|
||||
public ConcurrentHashSet(IEnumerable<T> collection)
|
||||
: this(collection, EqualityComparer<T>.Default) { }
|
||||
public ConcurrentHashSet(IEqualityComparer<T> comparer)
|
||||
: this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer) { }
|
||||
public ConcurrentHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
|
||||
: this(comparer)
|
||||
{
|
||||
if (collection == null) throw new ArgumentNullException(nameof(collection));
|
||||
InitializeFromCollection(collection);
|
||||
}
|
||||
public ConcurrentHashSet(int concurrencyLevel, IEnumerable<T> collection, IEqualityComparer<T> comparer)
|
||||
: this(concurrencyLevel, DefaultCapacity, false, comparer)
|
||||
{
|
||||
if (collection == null) throw new ArgumentNullException(nameof(collection));
|
||||
if (comparer == null) throw new ArgumentNullException(nameof(comparer));
|
||||
InitializeFromCollection(collection);
|
||||
}
|
||||
public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer<T> comparer)
|
||||
: this(concurrencyLevel, capacity, false, comparer) { }
|
||||
internal ConcurrentHashSet(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<T> comparer)
|
||||
{
|
||||
if (concurrencyLevel < 1) throw new ArgumentOutOfRangeException(nameof(concurrencyLevel));
|
||||
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
if (comparer == null) throw new ArgumentNullException(nameof(comparer));
|
||||
|
||||
if (capacity < concurrencyLevel)
|
||||
capacity = concurrencyLevel;
|
||||
|
||||
object[] locks = new object[concurrencyLevel];
|
||||
for (int i = 0; i < locks.Length; i++)
|
||||
locks[i] = new object();
|
||||
|
||||
int[] countPerLock = new int[locks.Length];
|
||||
Node[] buckets = new Node[capacity];
|
||||
_tables = new Tables(buckets, locks, countPerLock);
|
||||
|
||||
_comparer = comparer;
|
||||
_growLockArray = growLockArray;
|
||||
_budget = buckets.Length / locks.Length;
|
||||
}
|
||||
private void InitializeFromCollection(IEnumerable<T> collection)
|
||||
{
|
||||
foreach (var value in collection)
|
||||
{
|
||||
if (value == null) throw new ArgumentNullException("key");
|
||||
|
||||
if (!TryAddInternal(value, _comparer.GetHashCode(value), false))
|
||||
throw new ArgumentException();
|
||||
}
|
||||
|
||||
if (_budget == 0)
|
||||
_budget = _tables._buckets.Length / _tables._locks.Length;
|
||||
}
|
||||
|
||||
public bool ContainsKey(T value)
|
||||
{
|
||||
if (value == null) throw new ArgumentNullException("key");
|
||||
return ContainsKeyInternal(value, _comparer.GetHashCode(value));
|
||||
}
|
||||
private bool ContainsKeyInternal(T value, int hashcode)
|
||||
{
|
||||
Tables tables = _tables;
|
||||
|
||||
int bucketNo = GetBucket(hashcode, tables._buckets.Length);
|
||||
|
||||
Node n = Volatile.Read(ref tables._buckets[bucketNo]);
|
||||
|
||||
while (n != null)
|
||||
{
|
||||
if (hashcode == n._hashcode && _comparer.Equals(n._value, value))
|
||||
return true;
|
||||
n = n._next;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryAdd(T value)
|
||||
{
|
||||
if (value == null) throw new ArgumentNullException("key");
|
||||
return TryAddInternal(value, _comparer.GetHashCode(value), true);
|
||||
}
|
||||
private bool TryAddInternal(T value, int hashcode, bool acquireLock)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int bucketNo, lockNo;
|
||||
|
||||
Tables tables = _tables;
|
||||
GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
|
||||
|
||||
bool resizeDesired = false;
|
||||
bool lockTaken = false;
|
||||
try
|
||||
{
|
||||
if (acquireLock)
|
||||
Monitor.Enter(tables._locks[lockNo], ref lockTaken);
|
||||
|
||||
if (tables != _tables)
|
||||
continue;
|
||||
|
||||
Node prev = null;
|
||||
for (Node node = tables._buckets[bucketNo]; node != null; node = node._next)
|
||||
{
|
||||
if (hashcode == node._hashcode && _comparer.Equals(node._value, value))
|
||||
return false;
|
||||
prev = node;
|
||||
}
|
||||
|
||||
Volatile.Write(ref tables._buckets[bucketNo], new Node(value, hashcode, tables._buckets[bucketNo]));
|
||||
checked { tables._countPerLock[lockNo]++; }
|
||||
|
||||
if (tables._countPerLock[lockNo] > _budget)
|
||||
resizeDesired = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lockTaken)
|
||||
Monitor.Exit(tables._locks[lockNo]);
|
||||
}
|
||||
|
||||
if (resizeDesired)
|
||||
GrowTable(tables);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryRemove(T value)
|
||||
{
|
||||
if (value == null) throw new ArgumentNullException("key");
|
||||
return TryRemoveInternal(value);
|
||||
}
|
||||
private bool TryRemoveInternal(T value)
|
||||
{
|
||||
int hashcode = _comparer.GetHashCode(value);
|
||||
while (true)
|
||||
{
|
||||
Tables tables = _tables;
|
||||
|
||||
int bucketNo, lockNo;
|
||||
GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
|
||||
|
||||
lock (tables._locks[lockNo])
|
||||
{
|
||||
if (tables != _tables)
|
||||
continue;
|
||||
|
||||
Node prev = null;
|
||||
for (Node curr = tables._buckets[bucketNo]; curr != null; curr = curr._next)
|
||||
{
|
||||
if (hashcode == curr._hashcode && _comparer.Equals(curr._value, value))
|
||||
{
|
||||
if (prev == null)
|
||||
Volatile.Write(ref tables._buckets[bucketNo], curr._next);
|
||||
else
|
||||
prev._next = curr._next;
|
||||
|
||||
value = curr._value;
|
||||
tables._countPerLock[lockNo]--;
|
||||
return true;
|
||||
}
|
||||
prev = curr;
|
||||
}
|
||||
}
|
||||
|
||||
value = default(T);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
int locksAcquired = 0;
|
||||
try
|
||||
{
|
||||
AcquireAllLocks(ref locksAcquired);
|
||||
|
||||
Tables newTables = new Tables(new Node[DefaultCapacity], _tables._locks, new int[_tables._countPerLock.Length]);
|
||||
_tables = newTables;
|
||||
_budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReleaseLocks(0, locksAcquired);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerator<T> GetEnumerator()
|
||||
{
|
||||
Node[] buckets = _tables._buckets;
|
||||
|
||||
for (int i = 0; i < buckets.Length; i++)
|
||||
{
|
||||
Node current = Volatile.Read(ref buckets[i]);
|
||||
|
||||
while (current != null)
|
||||
{
|
||||
yield return current._value;
|
||||
current = current._next;
|
||||
}
|
||||
}
|
||||
}
|
||||
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
|
||||
private void GrowTable(Tables tables)
|
||||
{
|
||||
const int MaxArrayLength = 0X7FEFFFFF;
|
||||
int locksAcquired = 0;
|
||||
try
|
||||
{
|
||||
AcquireLocks(0, 1, ref locksAcquired);
|
||||
if (tables != _tables)
|
||||
return;
|
||||
|
||||
long approxCount = 0;
|
||||
for (int i = 0; i < tables._countPerLock.Length; i++)
|
||||
approxCount += tables._countPerLock[i];
|
||||
|
||||
if (approxCount < tables._buckets.Length / 4)
|
||||
{
|
||||
_budget = 2 * _budget;
|
||||
if (_budget < 0)
|
||||
_budget = int.MaxValue;
|
||||
return;
|
||||
}
|
||||
|
||||
int newLength = 0;
|
||||
bool maximizeTableSize = false;
|
||||
try
|
||||
{
|
||||
checked
|
||||
{
|
||||
newLength = tables._buckets.Length * 2 + 1;
|
||||
while (newLength % 3 == 0 || newLength % 5 == 0 || newLength % 7 == 0)
|
||||
newLength += 2;
|
||||
|
||||
if (newLength > MaxArrayLength)
|
||||
maximizeTableSize = true;
|
||||
}
|
||||
}
|
||||
catch (OverflowException)
|
||||
{
|
||||
maximizeTableSize = true;
|
||||
}
|
||||
|
||||
if (maximizeTableSize)
|
||||
{
|
||||
newLength = MaxArrayLength;
|
||||
_budget = int.MaxValue;
|
||||
}
|
||||
|
||||
AcquireLocks(1, tables._locks.Length, ref locksAcquired);
|
||||
|
||||
object[] newLocks = tables._locks;
|
||||
|
||||
if (_growLockArray && tables._locks.Length < MaxLockNumber)
|
||||
{
|
||||
newLocks = new object[tables._locks.Length * 2];
|
||||
Array.Copy(tables._locks, 0, newLocks, 0, tables._locks.Length);
|
||||
for (int i = tables._locks.Length; i < newLocks.Length; i++)
|
||||
newLocks[i] = new object();
|
||||
}
|
||||
|
||||
Node[] newBuckets = new Node[newLength];
|
||||
int[] newCountPerLock = new int[newLocks.Length];
|
||||
|
||||
for (int i = 0; i < tables._buckets.Length; i++)
|
||||
{
|
||||
Node current = tables._buckets[i];
|
||||
while (current != null)
|
||||
{
|
||||
Node next = current._next;
|
||||
int newBucketNo, newLockNo;
|
||||
GetBucketAndLockNo(current._hashcode, out newBucketNo, out newLockNo, newBuckets.Length, newLocks.Length);
|
||||
|
||||
newBuckets[newBucketNo] = new Node(current._value, current._hashcode, newBuckets[newBucketNo]);
|
||||
|
||||
checked { newCountPerLock[newLockNo]++; }
|
||||
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
|
||||
_budget = Math.Max(1, newBuckets.Length / newLocks.Length);
|
||||
_tables = new Tables(newBuckets, newLocks, newCountPerLock);
|
||||
}
|
||||
finally { ReleaseLocks(0, locksAcquired); }
|
||||
}
|
||||
|
||||
private void AcquireAllLocks(ref int locksAcquired)
|
||||
{
|
||||
AcquireLocks(0, 1, ref locksAcquired);
|
||||
AcquireLocks(1, _tables._locks.Length, ref locksAcquired);
|
||||
}
|
||||
private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
|
||||
{
|
||||
object[] locks = _tables._locks;
|
||||
|
||||
for (int i = fromInclusive; i < toExclusive; i++)
|
||||
{
|
||||
bool lockTaken = false;
|
||||
try
|
||||
{
|
||||
Monitor.Enter(locks[i], ref lockTaken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lockTaken)
|
||||
locksAcquired++;
|
||||
}
|
||||
}
|
||||
}
|
||||
private void ReleaseLocks(int fromInclusive, int toExclusive)
|
||||
{
|
||||
for (int i = fromInclusive; i < toExclusive; i++)
|
||||
Monitor.Exit(_tables._locks[i]);
|
||||
}
|
||||
}
|
||||
|
||||
//https://github.com/dotnet/corefx/blob/d0dc5fc099946adc1035b34a8b1f6042eddb0c75/src/System.Threading.Tasks.Parallel/src/System/Threading/PlatformHelper.cs
|
||||
//Copyright (c) .NET Foundation and Contributors
|
||||
internal static class PlatformHelper
|
||||
{
|
||||
private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 30000;
|
||||
private static volatile int s_processorCount;
|
||||
private static volatile int s_lastProcessorCountRefreshTicks;
|
||||
|
||||
internal static int ProcessorCount
|
||||
{
|
||||
get
|
||||
{
|
||||
int now = Environment.TickCount;
|
||||
if (s_processorCount == 0 || (now - s_lastProcessorCountRefreshTicks) >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS)
|
||||
{
|
||||
s_processorCount = Environment.ProcessorCount;
|
||||
s_lastProcessorCountRefreshTicks = now;
|
||||
}
|
||||
|
||||
return s_processorCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
src/Discord.Net.Core/Utils/DateTimeUtils.cs
Normal file
15
src/Discord.Net.Core/Utils/DateTimeUtils.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal static class DateTimeUtils
|
||||
{
|
||||
public static DateTimeOffset FromSnowflake(ulong value)
|
||||
=> DateTimeOffset.FromUnixTimeMilliseconds((long)((value >> 22) + 1420070400000UL));
|
||||
|
||||
public static DateTimeOffset FromTicks(long ticks)
|
||||
=> new DateTimeOffset(ticks, TimeSpan.Zero);
|
||||
public static DateTimeOffset? FromTicks(long? ticks)
|
||||
=> ticks != null ? new DateTimeOffset(ticks.Value, TimeSpan.Zero) : (DateTimeOffset?)null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal static class CollectionExtensions
|
||||
{
|
||||
public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> source)
|
||||
=> new ConcurrentDictionaryWrapper<TValue>(source.Select(x => x.Value), () => source.Count);
|
||||
public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TValue, TSource>(this IEnumerable<TValue> query, IReadOnlyCollection<TSource> source)
|
||||
=> new ConcurrentDictionaryWrapper<TValue>(query, () => source.Count);
|
||||
public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TValue>(this IEnumerable<TValue> query, Func<int> countFunc)
|
||||
=> new ConcurrentDictionaryWrapper<TValue>(query, countFunc);
|
||||
}
|
||||
|
||||
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
|
||||
internal struct ConcurrentDictionaryWrapper<TValue> : IReadOnlyCollection<TValue>
|
||||
{
|
||||
private readonly IEnumerable<TValue> _query;
|
||||
private readonly Func<int> _countFunc;
|
||||
|
||||
//It's okay that this count is affected by race conditions - we're wrapping a concurrent collection and that's to be expected
|
||||
public int Count => _countFunc();
|
||||
|
||||
public ConcurrentDictionaryWrapper(IEnumerable<TValue> query, Func<int> countFunc)
|
||||
{
|
||||
_query = query;
|
||||
_countFunc = countFunc;
|
||||
}
|
||||
|
||||
private string DebuggerDisplay => $"Count = {Count}";
|
||||
|
||||
public IEnumerator<TValue> GetEnumerator() => _query.GetEnumerator();
|
||||
IEnumerator IEnumerable.GetEnumerator() => _query.GetEnumerator();
|
||||
}
|
||||
}
|
||||
152
src/Discord.Net.Core/Utils/Extensions/Permissions.cs
Normal file
152
src/Discord.Net.Core/Utils/Extensions/Permissions.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Discord.Extensions
|
||||
{
|
||||
internal static class Permissions
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static PermValue GetValue(ulong allow, ulong deny, ChannelPermission bit)
|
||||
=> GetValue(allow, deny, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static PermValue GetValue(ulong allow, ulong deny, GuildPermission bit)
|
||||
=> GetValue(allow, deny, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static PermValue GetValue(ulong allow, ulong deny, byte bit)
|
||||
{
|
||||
if (HasBit(allow, bit))
|
||||
return PermValue.Allow;
|
||||
else if (HasBit(deny, bit))
|
||||
return PermValue.Deny;
|
||||
else
|
||||
return PermValue.Inherit;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GetValue(ulong value, ChannelPermission bit)
|
||||
=> GetValue(value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GetValue(ulong value, GuildPermission bit)
|
||||
=> GetValue(value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GetValue(ulong value, byte bit) => HasBit(value, bit);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong rawValue, bool? value, ChannelPermission bit)
|
||||
=> SetValue(ref rawValue, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong rawValue, bool? value, GuildPermission bit)
|
||||
=> SetValue(ref rawValue, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong rawValue, bool? value, byte bit)
|
||||
{
|
||||
if (value.HasValue)
|
||||
{
|
||||
if (value == true)
|
||||
SetBit(ref rawValue, bit);
|
||||
else
|
||||
UnsetBit(ref rawValue, bit);
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, ChannelPermission bit)
|
||||
=> SetValue(ref allow, ref deny, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, GuildPermission bit)
|
||||
=> SetValue(ref allow, ref deny, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, byte bit)
|
||||
{
|
||||
if (value.HasValue)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case PermValue.Allow:
|
||||
SetBit(ref allow, bit);
|
||||
UnsetBit(ref deny, bit);
|
||||
break;
|
||||
case PermValue.Deny:
|
||||
UnsetBit(ref allow, bit);
|
||||
SetBit(ref deny, bit);
|
||||
break;
|
||||
default:
|
||||
UnsetBit(ref allow, bit);
|
||||
UnsetBit(ref deny, bit);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static bool HasBit(ulong value, byte bit) => (value & (1U << bit)) != 0;
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetBit(ref ulong value, byte bit) => value |= (1U << bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void UnsetBit(ref ulong value, byte bit) => value &= ~(1U << bit);
|
||||
|
||||
public static ulong ResolveGuild(IGuild guild, IGuildUser user)
|
||||
{
|
||||
ulong resolvedPermissions = 0;
|
||||
|
||||
if (user.Id == guild.OwnerId)
|
||||
resolvedPermissions = GuildPermissions.All.RawValue; //Owners always have all permissions
|
||||
else
|
||||
{
|
||||
foreach (var role in user.RoleIds)
|
||||
resolvedPermissions |= guild.GetRole(role).Permissions.RawValue;
|
||||
if (GetValue(resolvedPermissions, GuildPermission.Administrator))
|
||||
resolvedPermissions = GuildPermissions.All.RawValue; //Administrators always have all permissions
|
||||
}
|
||||
return resolvedPermissions;
|
||||
}
|
||||
|
||||
/*public static ulong ResolveChannel(IGuildUser user, IGuildChannel channel)
|
||||
{
|
||||
return ResolveChannel(user, channel, ResolveGuild(user));
|
||||
}*/
|
||||
public static ulong ResolveChannel(IGuild guild, IGuildChannel channel, IGuildUser user, ulong guildPermissions)
|
||||
{
|
||||
ulong resolvedPermissions = 0;
|
||||
|
||||
ulong mask = ChannelPermissions.All(channel).RawValue;
|
||||
if (/*user.Id == user.Guild.OwnerId || */GetValue(guildPermissions, GuildPermission.Administrator))
|
||||
resolvedPermissions = mask; //Owners and administrators always have all permissions
|
||||
else
|
||||
{
|
||||
//Start with this user's guild permissions
|
||||
resolvedPermissions = guildPermissions;
|
||||
|
||||
OverwritePermissions? perms;
|
||||
var roleIds = user.RoleIds;
|
||||
if (roleIds.Count > 0)
|
||||
{
|
||||
ulong deniedPermissions = 0UL, allowedPermissions = 0UL;
|
||||
foreach (var roleId in roleIds)
|
||||
{
|
||||
perms = channel.GetPermissionOverwrite(guild.GetRole(roleId));
|
||||
if (perms != null)
|
||||
{
|
||||
deniedPermissions |= perms.Value.DenyValue;
|
||||
allowedPermissions |= perms.Value.AllowValue;
|
||||
}
|
||||
}
|
||||
resolvedPermissions = (resolvedPermissions & ~deniedPermissions) | allowedPermissions;
|
||||
}
|
||||
perms = channel.GetPermissionOverwrite(user);
|
||||
if (perms != null)
|
||||
resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue;
|
||||
|
||||
//TODO: C#7 Typeswitch candidate
|
||||
var textChannel = channel as ITextChannel;
|
||||
var voiceChannel = channel as IVoiceChannel;
|
||||
if (textChannel != null && !GetValue(resolvedPermissions, ChannelPermission.ReadMessages))
|
||||
resolvedPermissions = 0; //No read permission on a text channel removes all other permissions
|
||||
else if (voiceChannel != null && !GetValue(resolvedPermissions, ChannelPermission.Connect))
|
||||
resolvedPermissions = 0; //No connect permission on a voice channel removes all other permissions
|
||||
resolvedPermissions &= mask; //Ensure we didnt get any permissions this channel doesnt support (from guildPerms, for example)
|
||||
}
|
||||
|
||||
return resolvedPermissions;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal static class TaskCompletionSourceExtensions
|
||||
{
|
||||
public static Task<bool> TrySetResultAsync<T>(this TaskCompletionSource<T> source, T result)
|
||||
=> Task.Run(() => source.TrySetResult(result));
|
||||
public static Task<bool> TrySetExceptionAsync<T>(this TaskCompletionSource<T> source, Exception ex)
|
||||
=> Task.Run(() => source.TrySetException(ex));
|
||||
public static Task<bool> TrySetCanceledAsync<T>(this TaskCompletionSource<T> source)
|
||||
=> Task.Run(() => source.TrySetCanceled());
|
||||
}
|
||||
}
|
||||
195
src/Discord.Net.Core/Utils/MentionsHelper.cs
Normal file
195
src/Discord.Net.Core/Utils/MentionsHelper.cs
Normal file
@@ -0,0 +1,195 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal static class MentionsHelper
|
||||
{
|
||||
private static readonly Regex _userRegex = new Regex(@"<@!?([0-9]+)>", RegexOptions.Compiled);
|
||||
private static readonly Regex _channelRegex = new Regex(@"<#([0-9]+)>", RegexOptions.Compiled);
|
||||
private static readonly Regex _roleRegex = new Regex(@"<@&([0-9]+)>", RegexOptions.Compiled);
|
||||
|
||||
//If the system can't be positive a user doesn't have a nickname, assume useNickname = true (source: Jake)
|
||||
internal static string MentionUser(ulong id, bool useNickname = true) => useNickname ? $"<@!{id}>" : $"<@{id}>";
|
||||
internal static string MentionChannel(ulong id) => $"<#{id}>";
|
||||
internal static string MentionRole(ulong id) => $"<@&{id}>";
|
||||
|
||||
internal static ImmutableArray<TUser> GetUserMentions<TUser>(string text, IMessageChannel channel, IReadOnlyCollection<TUser> mentionedUsers)
|
||||
where TUser : class, IUser
|
||||
{
|
||||
var matches = _userRegex.Matches(text);
|
||||
var builder = ImmutableArray.CreateBuilder<TUser>(matches.Count);
|
||||
foreach (var match in matches.OfType<Match>())
|
||||
{
|
||||
ulong id;
|
||||
if (ulong.TryParse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
|
||||
{
|
||||
TUser user = null;
|
||||
|
||||
//Verify this user was actually mentioned
|
||||
foreach (var userMention in mentionedUsers)
|
||||
{
|
||||
if (userMention.Id == id)
|
||||
{
|
||||
user = channel?.GetCachedUser(id) as TUser;
|
||||
if (user == null) //User not found, fallback to basic mention info
|
||||
user = userMention;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (user != null)
|
||||
builder.Add(user);
|
||||
}
|
||||
}
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
internal static ImmutableArray<ulong> GetChannelMentions(string text, IGuild guild)
|
||||
{
|
||||
var matches = _channelRegex.Matches(text);
|
||||
var builder = ImmutableArray.CreateBuilder<ulong>(matches.Count);
|
||||
foreach (var match in matches.OfType<Match>())
|
||||
{
|
||||
ulong id;
|
||||
if (ulong.TryParse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
|
||||
builder.Add(id);
|
||||
}
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
internal static ImmutableArray<TRole> GetRoleMentions<TRole>(string text, IGuild guild)
|
||||
where TRole : class, IRole
|
||||
{
|
||||
var matches = _roleRegex.Matches(text);
|
||||
var builder = ImmutableArray.CreateBuilder<TRole>(matches.Count);
|
||||
foreach (var match in matches.OfType<Match>())
|
||||
{
|
||||
ulong id;
|
||||
if (ulong.TryParse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
|
||||
{
|
||||
var role = guild.GetRole(id) as TRole;
|
||||
if (role != null)
|
||||
builder.Add(role);
|
||||
}
|
||||
}
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
internal static string ResolveUserMentions(string text, IMessageChannel channel, IReadOnlyCollection<IUser> mentions, UserMentionHandling mode)
|
||||
{
|
||||
if (mode == UserMentionHandling.Ignore) return text;
|
||||
|
||||
return _userRegex.Replace(text, new MatchEvaluator(e =>
|
||||
{
|
||||
ulong id;
|
||||
if (ulong.TryParse(e.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
|
||||
{
|
||||
IUser user = null;
|
||||
foreach (var mention in mentions)
|
||||
{
|
||||
if (mention.Id == id)
|
||||
{
|
||||
user = mention;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (user != null)
|
||||
{
|
||||
string name = user.Username;
|
||||
|
||||
var guildUser = user as IGuildUser;
|
||||
if (e.Value[2] == '!')
|
||||
{
|
||||
if (guildUser != null && guildUser.Nickname != null)
|
||||
name = guildUser.Nickname;
|
||||
}
|
||||
|
||||
switch (mode)
|
||||
{
|
||||
case UserMentionHandling.Remove:
|
||||
default:
|
||||
return "";
|
||||
case UserMentionHandling.Name:
|
||||
return $"@{name}";
|
||||
case UserMentionHandling.NameAndDiscriminator:
|
||||
return $"@{name}#{user.Discriminator}";
|
||||
}
|
||||
}
|
||||
}
|
||||
return e.Value;
|
||||
}));
|
||||
}
|
||||
internal static string ResolveChannelMentions(string text, IGuild guild, ChannelMentionHandling mode)
|
||||
{
|
||||
if (mode == ChannelMentionHandling.Ignore) return text;
|
||||
|
||||
return _channelRegex.Replace(text, new MatchEvaluator(e =>
|
||||
{
|
||||
ulong id;
|
||||
if (ulong.TryParse(e.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case ChannelMentionHandling.Remove:
|
||||
return "";
|
||||
case ChannelMentionHandling.Name:
|
||||
IGuildChannel channel = null;
|
||||
channel = guild.GetCachedChannel(id);
|
||||
if (channel != null)
|
||||
return $"#{channel.Name}";
|
||||
else
|
||||
return $"#deleted-channel";
|
||||
}
|
||||
}
|
||||
return e.Value;
|
||||
}));
|
||||
}
|
||||
internal static string ResolveRoleMentions(string text, IReadOnlyCollection<IRole> mentions, RoleMentionHandling mode)
|
||||
{
|
||||
if (mode == RoleMentionHandling.Ignore) return text;
|
||||
|
||||
return _roleRegex.Replace(text, new MatchEvaluator(e =>
|
||||
{
|
||||
ulong id;
|
||||
if (ulong.TryParse(e.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case RoleMentionHandling.Remove:
|
||||
return "";
|
||||
case RoleMentionHandling.Name:
|
||||
IRole role = null;
|
||||
foreach (var mention in mentions)
|
||||
{
|
||||
if (mention.Id == id)
|
||||
{
|
||||
role = mention;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (role != null)
|
||||
return $"@{role.Name}";
|
||||
else
|
||||
return $"@deleted-role";
|
||||
}
|
||||
}
|
||||
return e.Value;
|
||||
}));
|
||||
}
|
||||
internal static string ResolveEveryoneMentions(string text, EveryoneMentionHandling mode)
|
||||
{
|
||||
if (mode == EveryoneMentionHandling.Ignore) return text;
|
||||
|
||||
switch (mode)
|
||||
{
|
||||
case EveryoneMentionHandling.Sanitize:
|
||||
return text.Replace("@everyone", "@\x200beveryone").Replace("@here", "@\x200bhere");
|
||||
case EveryoneMentionHandling.Remove:
|
||||
default:
|
||||
return text.Replace("@everyone", "").Replace("@here", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
22
src/Discord.Net.Core/Utils/Paging/Page.cs
Normal file
22
src/Discord.Net.Core/Utils/Paging/Page.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal class Page<T> : IReadOnlyCollection<T>
|
||||
{
|
||||
private readonly IReadOnlyCollection<T> _items;
|
||||
public int Index { get; }
|
||||
|
||||
public Page(PageInfo info, IEnumerable<T> source)
|
||||
{
|
||||
Index = info.Page;
|
||||
_items = source.ToImmutableArray();
|
||||
}
|
||||
|
||||
int IReadOnlyCollection<T>.Count => _items.Count;
|
||||
IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator();
|
||||
IEnumerator<T> IEnumerable<T>.GetEnumerator() => _items.GetEnumerator();
|
||||
}
|
||||
}
|
||||
20
src/Discord.Net.Core/Utils/Paging/PageInfo.cs
Normal file
20
src/Discord.Net.Core/Utils/Paging/PageInfo.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
namespace Discord
|
||||
{
|
||||
internal class PageInfo
|
||||
{
|
||||
public int Page { get; set; }
|
||||
public ulong? Position { get; set; }
|
||||
public uint? Count { get; set; }
|
||||
public int PageSize { get; set; }
|
||||
public uint? Remaining { get; set; }
|
||||
|
||||
internal PageInfo(ulong? pos, uint? count, int pageSize)
|
||||
{
|
||||
Page = 1;
|
||||
Position = pos;
|
||||
Count = count;
|
||||
Remaining = count;
|
||||
PageSize = pageSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
67
src/Discord.Net.Core/Utils/Paging/PagedEnumerator.cs
Normal file
67
src/Discord.Net.Core/Utils/Paging/PagedEnumerator.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal class PagedAsyncEnumerable<T> : IAsyncEnumerable<IReadOnlyCollection<T>>
|
||||
{
|
||||
public int PageSize { get; }
|
||||
|
||||
private readonly ulong? _start;
|
||||
private readonly uint? _count;
|
||||
private readonly Func<PageInfo, CancellationToken, Task<IReadOnlyCollection<T>>> _getPage;
|
||||
private readonly Action<PageInfo, IReadOnlyCollection<T>> _nextPage;
|
||||
|
||||
public PagedAsyncEnumerable(int pageSize, Func<PageInfo, CancellationToken, Task<IReadOnlyCollection<T>>> getPage, Action<PageInfo, IReadOnlyCollection<T>> nextPage = null,
|
||||
ulong? start = null, uint? count = null)
|
||||
{
|
||||
PageSize = pageSize;
|
||||
_start = start;
|
||||
_count = count;
|
||||
|
||||
_getPage = getPage;
|
||||
_nextPage = nextPage;
|
||||
}
|
||||
|
||||
public IAsyncEnumerator<IReadOnlyCollection<T>> GetEnumerator() => new Enumerator(this);
|
||||
internal class Enumerator : IAsyncEnumerator<IReadOnlyCollection<T>>
|
||||
{
|
||||
private readonly PagedAsyncEnumerable<T> _source;
|
||||
private readonly PageInfo _info;
|
||||
|
||||
public IReadOnlyCollection<T> Current { get; private set; }
|
||||
|
||||
public Enumerator(PagedAsyncEnumerable<T> source)
|
||||
{
|
||||
_source = source;
|
||||
_info = new PageInfo(source._start, source._count, source.PageSize);
|
||||
}
|
||||
|
||||
public async Task<bool> MoveNext(CancellationToken cancelToken)
|
||||
{
|
||||
var data = await _source._getPage(_info, cancelToken);
|
||||
Current = new Page<T>(_info, data);
|
||||
|
||||
_info.Page++;
|
||||
_info.Remaining -= (uint)Current.Count;
|
||||
_info.PageSize = _info.Remaining != null ? (int)Math.Min(_info.Remaining.Value, (ulong)_source.PageSize) : _source.PageSize;
|
||||
_source?._nextPage(_info, data);
|
||||
|
||||
return _info.Remaining > 0;
|
||||
}
|
||||
|
||||
public void Dispose() { Current = null; }
|
||||
}
|
||||
}
|
||||
|
||||
public static class PagedAsyncEnumerable
|
||||
{
|
||||
public static async Task<IEnumerable<T>> Flatten<T>(this IAsyncEnumerable<IReadOnlyCollection<T>> source)
|
||||
{
|
||||
return (await source.ToArray().ConfigureAwait(false)).SelectMany(x => x);
|
||||
}
|
||||
}
|
||||
}
|
||||
154
src/Discord.Net.Core/Utils/Permissions.cs
Normal file
154
src/Discord.Net.Core/Utils/Permissions.cs
Normal file
@@ -0,0 +1,154 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal static class Permissions
|
||||
{
|
||||
public const int MaxBits = 53;
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static PermValue GetValue(ulong allow, ulong deny, ChannelPermission bit)
|
||||
=> GetValue(allow, deny, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static PermValue GetValue(ulong allow, ulong deny, GuildPermission bit)
|
||||
=> GetValue(allow, deny, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static PermValue GetValue(ulong allow, ulong deny, byte bit)
|
||||
{
|
||||
if (HasBit(allow, bit))
|
||||
return PermValue.Allow;
|
||||
else if (HasBit(deny, bit))
|
||||
return PermValue.Deny;
|
||||
else
|
||||
return PermValue.Inherit;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GetValue(ulong value, ChannelPermission bit)
|
||||
=> GetValue(value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GetValue(ulong value, GuildPermission bit)
|
||||
=> GetValue(value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool GetValue(ulong value, byte bit) => HasBit(value, bit);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong rawValue, bool? value, ChannelPermission bit)
|
||||
=> SetValue(ref rawValue, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong rawValue, bool? value, GuildPermission bit)
|
||||
=> SetValue(ref rawValue, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong rawValue, bool? value, byte bit)
|
||||
{
|
||||
if (value.HasValue)
|
||||
{
|
||||
if (value == true)
|
||||
SetBit(ref rawValue, bit);
|
||||
else
|
||||
UnsetBit(ref rawValue, bit);
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, ChannelPermission bit)
|
||||
=> SetValue(ref allow, ref deny, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, GuildPermission bit)
|
||||
=> SetValue(ref allow, ref deny, value, (byte)bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, byte bit)
|
||||
{
|
||||
if (value.HasValue)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case PermValue.Allow:
|
||||
SetBit(ref allow, bit);
|
||||
UnsetBit(ref deny, bit);
|
||||
break;
|
||||
case PermValue.Deny:
|
||||
UnsetBit(ref allow, bit);
|
||||
SetBit(ref deny, bit);
|
||||
break;
|
||||
default:
|
||||
UnsetBit(ref allow, bit);
|
||||
UnsetBit(ref deny, bit);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static bool HasBit(ulong value, byte bit) => (value & (1U << bit)) != 0;
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void SetBit(ref ulong value, byte bit) => value |= (1U << bit);
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void UnsetBit(ref ulong value, byte bit) => value &= ~(1U << bit);
|
||||
|
||||
public static ulong ResolveGuild(IGuild guild, IGuildUser user)
|
||||
{
|
||||
ulong resolvedPermissions = 0;
|
||||
|
||||
if (user.Id == guild.OwnerId)
|
||||
resolvedPermissions = GuildPermissions.All.RawValue; //Owners always have all permissions
|
||||
else
|
||||
{
|
||||
foreach (var roleId in user.RoleIds)
|
||||
resolvedPermissions |= guild.GetRole(roleId)?.Permissions.RawValue ?? 0;
|
||||
if (GetValue(resolvedPermissions, GuildPermission.Administrator))
|
||||
resolvedPermissions = GuildPermissions.All.RawValue; //Administrators always have all permissions
|
||||
}
|
||||
return resolvedPermissions;
|
||||
}
|
||||
|
||||
/*public static ulong ResolveChannel(IGuildUser user, IGuildChannel channel)
|
||||
{
|
||||
return ResolveChannel(user, channel, ResolveGuild(user));
|
||||
}*/
|
||||
public static ulong ResolveChannel(IGuild guild, IGuildUser user, IGuildChannel channel, ulong guildPermissions)
|
||||
{
|
||||
ulong resolvedPermissions = 0;
|
||||
|
||||
ulong mask = ChannelPermissions.All(channel).RawValue;
|
||||
if (/*user.Id == user.Guild.OwnerId || */GetValue(guildPermissions, GuildPermission.Administrator))
|
||||
resolvedPermissions = mask; //Owners and administrators always have all permissions
|
||||
else
|
||||
{
|
||||
//Start with this user's guild permissions
|
||||
resolvedPermissions = guildPermissions;
|
||||
|
||||
OverwritePermissions? perms;
|
||||
var roleIds = user.RoleIds;
|
||||
if (roleIds.Count > 0)
|
||||
{
|
||||
ulong deniedPermissions = 0UL, allowedPermissions = 0UL;
|
||||
foreach (var roleId in roleIds)
|
||||
{
|
||||
perms = channel.GetPermissionOverwrite(guild.GetRole(roleId));
|
||||
if (perms != null)
|
||||
{
|
||||
deniedPermissions |= perms.Value.DenyValue;
|
||||
allowedPermissions |= perms.Value.AllowValue;
|
||||
}
|
||||
}
|
||||
resolvedPermissions = (resolvedPermissions & ~deniedPermissions) | allowedPermissions;
|
||||
}
|
||||
perms = channel.GetPermissionOverwrite(user);
|
||||
if (perms != null)
|
||||
resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue;
|
||||
|
||||
//TODO: C#7 Typeswitch candidate
|
||||
var textChannel = channel as ITextChannel;
|
||||
var voiceChannel = channel as IVoiceChannel;
|
||||
if (textChannel != null && !GetValue(resolvedPermissions, ChannelPermission.ReadMessages))
|
||||
resolvedPermissions = 0; //No read permission on a text channel removes all other permissions
|
||||
else if (voiceChannel != null && !GetValue(resolvedPermissions, ChannelPermission.Connect))
|
||||
resolvedPermissions = 0; //No connect permission on a voice channel removes all other permissions
|
||||
resolvedPermissions &= mask; //Ensure we didnt get any permissions this channel doesnt support (from guildPerms, for example)
|
||||
}
|
||||
|
||||
return resolvedPermissions;
|
||||
}
|
||||
}
|
||||
}
|
||||
151
src/Discord.Net.Core/Utils/Preconditions.cs
Normal file
151
src/Discord.Net.Core/Utils/Preconditions.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
|
||||
namespace Discord
|
||||
{
|
||||
internal static class Preconditions
|
||||
{
|
||||
//Objects
|
||||
public static void NotNull<T>(T obj, string name) where T : class { if (obj == null) throw new ArgumentNullException(name); }
|
||||
public static void NotNull<T>(Optional<T> obj, string name) where T : class { if (obj.IsSpecified && obj.Value == null) throw new ArgumentNullException(name); }
|
||||
|
||||
//Strings
|
||||
public static void NotEmpty(string obj, string name) { if (obj.Length == 0) throw new ArgumentException("Argument cannot be empty.", name); }
|
||||
public static void NotEmpty(Optional<string> obj, string name) { if (obj.IsSpecified && obj.Value.Length == 0) throw new ArgumentException("Argument cannot be empty.", name); }
|
||||
public static void NotNullOrEmpty(string obj, string name)
|
||||
{
|
||||
if (obj == null)
|
||||
throw new ArgumentNullException(name);
|
||||
if (obj.Length == 0)
|
||||
throw new ArgumentException("Argument cannot be empty.", name);
|
||||
}
|
||||
public static void NotNullOrEmpty(Optional<string> obj, string name)
|
||||
{
|
||||
if (obj.IsSpecified)
|
||||
{
|
||||
if (obj.Value == null)
|
||||
throw new ArgumentNullException(name);
|
||||
if (obj.Value.Length == 0)
|
||||
throw new ArgumentException("Argument cannot be empty.", name);
|
||||
}
|
||||
}
|
||||
public static void NotNullOrWhitespace(string obj, string name)
|
||||
{
|
||||
if (obj == null)
|
||||
throw new ArgumentNullException(name);
|
||||
if (obj.Trim().Length == 0)
|
||||
throw new ArgumentException("Argument cannot be blank.", name);
|
||||
}
|
||||
public static void NotNullOrWhitespace(Optional<string> obj, string name)
|
||||
{
|
||||
if (obj.IsSpecified)
|
||||
{
|
||||
if (obj.Value == null)
|
||||
throw new ArgumentNullException(name);
|
||||
if (obj.Value.Trim().Length == 0)
|
||||
throw new ArgumentException("Argument cannot be blank.", name);
|
||||
}
|
||||
}
|
||||
|
||||
//Numerics
|
||||
public static void NotEqual(sbyte obj, sbyte value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(byte obj, byte value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(short obj, short value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(ushort obj, ushort value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(int obj, int value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(uint obj, uint value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(long obj, long value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(ulong obj, ulong value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<sbyte> obj, sbyte value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<byte> obj, byte value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<short> obj, short value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<ushort> obj, ushort value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<int> obj, int value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<uint> obj, uint value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<long> obj, long value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<ulong> obj, ulong value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(sbyte? obj, sbyte value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(byte? obj, byte value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(short? obj, short value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(ushort? obj, ushort value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(int? obj, int value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(uint? obj, uint value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(long? obj, long value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(ulong? obj, ulong value, string name) { if (obj == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<sbyte?> obj, sbyte value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<byte?> obj, byte value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<short?> obj, short value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<ushort?> obj, ushort value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<int?> obj, int value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<uint?> obj, uint value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<long?> obj, long value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void NotEqual(Optional<ulong?> obj, ulong value, string name) { if (obj.IsSpecified && obj.Value == value) throw new ArgumentOutOfRangeException(name); }
|
||||
|
||||
public static void AtLeast(sbyte obj, sbyte value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(byte obj, byte value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(short obj, short value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(ushort obj, ushort value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(int obj, int value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(uint obj, uint value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(long obj, long value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(ulong obj, ulong value, string name) { if (obj < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<sbyte> obj, sbyte value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<byte> obj, byte value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<short> obj, short value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<ushort> obj, ushort value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<int> obj, int value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<uint> obj, uint value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<long> obj, long value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtLeast(Optional<ulong> obj, ulong value, string name) { if (obj.IsSpecified && obj.Value < value) throw new ArgumentOutOfRangeException(name); }
|
||||
|
||||
public static void GreaterThan(sbyte obj, sbyte value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(byte obj, byte value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(short obj, short value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(ushort obj, ushort value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(int obj, int value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(uint obj, uint value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(long obj, long value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(ulong obj, ulong value, string name) { if (obj <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<sbyte> obj, sbyte value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<byte> obj, byte value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<short> obj, short value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<ushort> obj, ushort value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<int> obj, int value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<uint> obj, uint value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<long> obj, long value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void GreaterThan(Optional<ulong> obj, ulong value, string name) { if (obj.IsSpecified && obj.Value <= value) throw new ArgumentOutOfRangeException(name); }
|
||||
|
||||
public static void AtMost(sbyte obj, sbyte value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(byte obj, byte value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(short obj, short value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(ushort obj, ushort value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(int obj, int value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(uint obj, uint value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(long obj, long value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(ulong obj, ulong value, string name) { if (obj > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<sbyte> obj, sbyte value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<byte> obj, byte value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<short> obj, short value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<ushort> obj, ushort value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<int> obj, int value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<uint> obj, uint value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<long> obj, long value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void AtMost(Optional<ulong> obj, ulong value, string name) { if (obj.IsSpecified && obj.Value > value) throw new ArgumentOutOfRangeException(name); }
|
||||
|
||||
public static void LessThan(sbyte obj, sbyte value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(byte obj, byte value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(short obj, short value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(ushort obj, ushort value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(int obj, int value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(uint obj, uint value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(long obj, long value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(ulong obj, ulong value, string name) { if (obj >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<sbyte> obj, sbyte value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<byte> obj, byte value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<short> obj, short value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<ushort> obj, ushort value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<int> obj, int value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<uint> obj, uint value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<long> obj, long value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
public static void LessThan(Optional<ulong> obj, ulong value, string name) { if (obj.IsSpecified && obj.Value >= value) throw new ArgumentOutOfRangeException(name); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user