diff --git a/src/SuccincT/Parsers/EnumCharParser.cs b/src/SuccincT/Parsers/EnumCharParser.cs new file mode 100644 index 0000000..9ed160d --- /dev/null +++ b/src/SuccincT/Parsers/EnumCharParser.cs @@ -0,0 +1,32 @@ +using SuccincT.Options; +using System; + +namespace SuccincT.Parsers +{ + /// + /// An enum parser that handles enums that are mapped to chars + /// + public static class EnumCharParser + { + /// + /// Parses an enum that is mapped to a char + /// + /// Enum type + /// source char + /// Option for the parsed enum + /// If T is not of an Enum Type + public static Option TryParsEnum(this char source) where T : struct + { + var sourceAsInt = (int)source; + + // Since TryParse will return true even for ints that don't + // correspond to valid enum values, need to check using IsDefined first + if (!Enum.IsDefined(typeof(T), sourceAsInt)) + { + return Option.None(); + } + + return sourceAsInt.ToString().TryParseEnum(); + } + } +} diff --git a/tests/SuccincT.Tests/SuccincT/EnumParsers/EnumCharParserTests.cs b/tests/SuccincT.Tests/SuccincT/EnumParsers/EnumCharParserTests.cs new file mode 100644 index 0000000..f94d487 --- /dev/null +++ b/tests/SuccincT.Tests/SuccincT/EnumParsers/EnumCharParserTests.cs @@ -0,0 +1,80 @@ +using NUnit.Framework; +using System; +using SuccincT.Options; +using SuccincT.Parsers; +using static NUnit.Framework.Assert; + +namespace SuccincTTests.SuccincT.EnumParsers +{ + [TestFixture] + public class EnumCharParserTests + { + private enum TestType + { + Foo = 'F', + Bar = 'B' + } + + private enum NotCharType + { + Foo, + Bar + } + + private struct JustAStruct + { + + } + + [Test] + public void NonEnumShouldThrowException() + { + // GIVEN a char + + // WHEN it is parsed into a type that is not an enum + Action action = () => + { + 'F'.TryParsEnum(); + }; + + // THEN an argument exception should be thrown + Throws(new TestDelegate(action), "an argument exception should have been thrown"); + } + + [Test] + public void EnumNotKeyedToCharShouldReturnNone() + { + // GIVEN a char + // WHEN it is parsed into an enum type that is not keyed to chars + var result = 'C'.TryParsEnum(); + + // THEN it should return option none + AreEqual(Option.None(), result, "if the enum is not keyed to chars, it should return none"); + } + + [Test] + public void InvalidValueReturnsNone() + { + // GIVEN a char + // WHEN it is parsed into an enum type that doesn't have a corresponding value + var result = 'C'.TryParsEnum(); + + // THEN it should return option none + AreEqual(Option.None(),result, "if the char doesn't correspond to an enum value, it should return none"); + } + + [Test] + public void ValidCharReturnsProperEnumValue() + { + // GIVEN a char + // WHEN it is parsed into an enum type with the corresponding char value + var result = 'F'.TryParsEnum(); + + // THEN the corresponding enum value option should be returned + AreEqual(Option.Some(TestType.Foo), result, + "result should have returned some with the correct enum value"); + } + + + } +}