feat: Add enum extension method for cycling to next enum value

This commit is contained in:
Austin Noska
2021-04-13 12:09:31 -04:00
parent 8cdddc94bc
commit 43fd348fae
4 changed files with 51 additions and 0 deletions

View File

@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## [Unreleased]
### Added
- Added enum extension method for cycling to the next enum value
- Added GetLocalTimeZoneName method to IcdEnvironment
- Added MatchAny method to RegexUtils
- Added OnSystemDeviceAddedRemoved and associated raise methods to IcdEnvironment for NETSTANDARD

View File

@@ -32,5 +32,17 @@ namespace ICD.Common.Utils.Tests.Extensions
{
Assert.AreEqual(expected, value.HasFlags(flags));
}
[TestCase(eTestEnum.A, eTestEnum.B)]
[TestCase(eTestEnum.B, eTestEnum.C)]
[TestCase(eTestEnum.C, eTestEnum.A)]
[TestCase(eTestEnum.A | eTestEnum.B, null)]
public void CycleNextTest(eTestEnum value, eTestEnum? expected)
{
if (EnumUtils.HasMultipleFlags(value))
Assert.Catch(typeof(InvalidOperationException), () => value.CycleNext());
else
Assert.AreEqual(expected, value.CycleNext());
}
}
}

View File

@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ICD.Common.Properties;
namespace ICD.Common.Utils.Extensions
@@ -83,5 +85,25 @@ namespace ICD.Common.Utils.Extensions
{
return EnumUtils.ToStringUndefined(extends);
}
/// <summary>
/// Returns the next defined enum value for the enum type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <returns></returns>
public static T CycleNext<T>(this T extends)
where T : struct, IConvertible
{
if (EnumUtils.IsFlagsEnum(typeof(T)) && !EnumUtils.HasSingleFlag(extends))
throw new InvalidOperationException(string.Format("Cannot cycle enum with multiple flags - {0}", extends));
IEnumerable<T> values = EnumUtils.GetValues<T>();
IList<T> list = values as IList<T> ?? values.ToArray();
int index = list.BinarySearch(extends);
return index == list.Count - 1 ? list[0] : list[index + 1];
}
}
}

View File

@@ -349,6 +349,22 @@ namespace ICD.Common.Utils.Extensions
#region Binary Search
/// <summary>
/// Returns the index of the item in the list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <param name="item"></param>
/// <returns></returns>
[PublicAPI]
public static int BinarySearch<T>([NotNull] this IList<T> extends, T item)
{
if (extends == null)
throw new ArgumentNullException("extends");
return extends.BinarySearch(item, Comparer<T>.Default);
}
/// <summary>
/// Returns the index of the item in the list.
/// </summary>