1 //
2 // Copyright (c) 2010-2023 Antmicro
3 // Copyright (c) 2011-2015 Realtime Embedded
4 //
5 // This file is licensed under the MIT License.
6 // Full license text is available in 'licenses/MIT.txt'.
7 //
8 using System;
9 using System.Linq.Expressions;
10 
11 namespace Antmicro.Renode.Utilities
12 {
13     static class EnumConverter<TEnum> where TEnum : struct, IConvertible
14     {
15         public static readonly Func<ulong, TEnum> ToEnum = GenerateEnumConverter();
16 
17         public static readonly Func<TEnum, uint> ToUInt32 = GenerateUInt32Converter();
18 
19         public static readonly Func<TEnum, ulong> ToUInt64 = GenerateUInt64Converter();
20 
GenerateEnumConverter()21         private static Func<ulong, TEnum> GenerateEnumConverter()
22         {
23             var parameter = Expression.Parameter(typeof(ulong));
24             var dynamicMethod = Expression.Lambda<Func<ulong, TEnum>>(
25                 Expression.Convert(parameter, typeof(TEnum)),
26                 parameter);
27             return dynamicMethod.Compile();
28         }
29 
GenerateUInt32Converter()30         private static Func<TEnum, uint> GenerateUInt32Converter()
31         {
32             var parameter = Expression.Parameter(typeof(TEnum));
33             var dynamicMethod = Expression.Lambda<Func<TEnum, uint>>(
34                 Expression.Convert(parameter, typeof(uint)),
35                 parameter);
36             return dynamicMethod.Compile();
37         }
38 
GenerateUInt64Converter()39         private static Func<TEnum, ulong> GenerateUInt64Converter()
40         {
41             var parameter = Expression.Parameter(typeof(TEnum));
42             var dynamicMethod = Expression.Lambda<Func<TEnum, ulong>>(
43                 Expression.Convert(parameter, typeof(ulong)),
44                 parameter);
45             return dynamicMethod.Compile();
46         }
47     }
48 }
49