Improve array conversion for paramslist

This commit is contained in:
RogueException
2016-08-20 20:57:25 -03:00
parent 432cecc7b2
commit cc9e1c1a65

View File

@@ -1,8 +1,10 @@
using System.Collections.Immutable; using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Generic;
using System;
namespace Discord.Commands namespace Discord.Commands
{ {
@@ -15,6 +17,9 @@ namespace Discord.Commands
QuotedParameter QuotedParameter
} }
private static readonly MethodInfo _convertArrayMethod = typeof(CommandParser).GetTypeInfo().GetDeclaredMethod(nameof(ConvertParamsList));
private static readonly ConcurrentDictionary<Type, Func<List<object>, object>> _arrayConverters = new ConcurrentDictionary<Type, Func<List<object>, object>>();
public static async Task<ParseResult> ParseArgs(Command command, IMessage context, string input, int startPos) public static async Task<ParseResult> ParseArgs(Command command, IMessage context, string input, int startPos)
{ {
CommandParameter curParam = null; CommandParameter curParam = null;
@@ -122,11 +127,12 @@ namespace Discord.Commands
if (curPos == endPos) if (curPos == endPos)
{ {
Array realParams = Array.CreateInstance(curParam.ElementType, paramsList.Count); var func = _arrayConverters.GetOrAdd(curParam.ElementType, t =>
for (int i = 0; i < paramsList.Count; i++) {
realParams.SetValue(Convert.ChangeType(paramsList[i], curParam.ElementType), i); var method = _convertArrayMethod.MakeGenericMethod(t);
return (Func<List<object>, object>)method.CreateDelegate(typeof(Func<List<object>, object>));
argList.Add(realParams); });
argList.Add(func.Invoke(paramsList));
curParam = null; curParam = null;
curPart = ParserPart.None; curPart = ParserPart.None;
@@ -169,5 +175,13 @@ namespace Discord.Commands
return ParseResult.FromSuccess(argList.ToImmutable()); return ParseResult.FromSuccess(argList.ToImmutable());
} }
private static T[] ConvertParamsList<T>(List<object> paramsList)
{
var array = new T[paramsList.Count];
for (int i = 0; i < array.Length; i++)
array[i] = (T)paramsList[i];
return array;
}
} }
} }