summary refs log tree commit diff
path: root/crypto/src/util/Enums.cs
blob: c369511d40e0d81c17bc3602f9176b7c7519bc6b (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;

#if PORTABLE
using System.Collections;
using System.Reflection;
#endif

using Org.BouncyCastle.Utilities.Date;

namespace Org.BouncyCastle.Utilities
{
    internal abstract class Enums
    {
        internal static Enum GetEnumValue(System.Type enumType, string s)
        {
            if (!IsEnumType(enumType))
                throw new ArgumentException("Not an enumeration type", "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(System.Type enumType)
        {
            if (!IsEnumType(enumType))
                throw new ArgumentException("Not an enumeration type", "enumType");

            return Enum.GetValues(enumType);
        }

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

        internal static bool IsEnumType(System.Type t)
        {
#if NEW_REFLECTION
            return t.GetTypeInfo().IsEnum;
#else
            return t.IsEnum;
#endif
        }
    }
}