summary refs log tree commit diff
path: root/crypto/src/util/Enums.cs
blob: fb685e2a7dac968f9f385d42dbd986f2e6317377 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;

using Org.BouncyCastle.Utilities.Date;

namespace Org.BouncyCastle.Utilities
{
    internal abstract class Enums
    {
        internal static Enum GetEnumValue(Type enumType, string s)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException("Not an enumeration type", nameof(enumType));

            // We only want to parse single named constants
            if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0)
            {
                s = s.Replace('-', '_');
                s = s.Replace('/', '_');

                return (Enum)Enum.Parse(enumType, s, false);
            }

            throw new ArgumentException();
        }

        internal static Array GetEnumValues(Type enumType)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException("Not an enumeration type", nameof(enumType));

            return Enum.GetValues(enumType);
        }

        internal static Enum GetArbitraryValue(Type enumType)
        {
            Array values = GetEnumValues(enumType);
            int pos = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length;
            return (Enum)values.GetValue(pos);
        }
    }
}