Cleaned up TypeReaders

This commit is contained in:
RogueException
2016-07-26 19:01:51 -03:00
parent c8a84a05b8
commit 4a06753990
5 changed files with 100 additions and 118 deletions

View File

@@ -7,31 +7,13 @@ using System.Threading.Tasks;
namespace Discord.Commands
{
delegate bool TryParseDelegate<T>(string str, out T value);
internal static class EnumTypeReader
{
private static readonly IReadOnlyDictionary<Type, object> _parsers;
static EnumTypeReader()
{
var parserBuilder = ImmutableDictionary.CreateBuilder<Type, object>();
parserBuilder[typeof(sbyte)] = (TryParseDelegate<sbyte>)sbyte.TryParse;
parserBuilder[typeof(byte)] = (TryParseDelegate<byte>)byte.TryParse;
parserBuilder[typeof(short)] = (TryParseDelegate<short>)short.TryParse;
parserBuilder[typeof(ushort)] = (TryParseDelegate<ushort>)ushort.TryParse;
parserBuilder[typeof(int)] = (TryParseDelegate<int>)int.TryParse;
parserBuilder[typeof(uint)] = (TryParseDelegate<uint>)uint.TryParse;
parserBuilder[typeof(long)] = (TryParseDelegate<long>)long.TryParse;
parserBuilder[typeof(ulong)] = (TryParseDelegate<ulong>)ulong.TryParse;
_parsers = parserBuilder.ToImmutable();
}
{
public static TypeReader GetReader(Type type)
{
Type baseType = Enum.GetUnderlyingType(type);
var constructor = typeof(EnumTypeReader<>).MakeGenericType(baseType).GetTypeInfo().DeclaredConstructors.First();
return (TypeReader)constructor.Invoke(new object[] { type, _parsers[baseType] });
return (TypeReader)constructor.Invoke(new object[] { type, PrimitiveParsers.Get(baseType) });
}
}

View File

@@ -1,17 +0,0 @@
using System;
using System.Threading.Tasks;
namespace Discord.Commands
{
internal class GenericTypeReader : TypeReader
{
private readonly Func<IMessage, string, Task<TypeReaderResult>> _action;
public GenericTypeReader(Func<IMessage, string, Task<TypeReaderResult>> action)
{
_action = action;
}
public override Task<TypeReaderResult> Read(IMessage context, string input) => _action(context, input);
}
}

View File

@@ -0,0 +1,23 @@
using System.Threading.Tasks;
namespace Discord.Commands
{
internal class SimpleTypeReader<T> : TypeReader
{
private readonly TryParseDelegate<T> _tryParse;
public SimpleTypeReader()
{
_tryParse = PrimitiveParsers.Get<T>();
}
public override Task<TypeReaderResult> Read(IMessage context, string input)
{
T value;
if (_tryParse(input, out value))
return Task.FromResult(TypeReaderResult.FromSuccess(value));
else
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"Failed to parse {typeof(T).Name}"));
}
}
}