コード例 #1
0
        public void TryEnumLookup()
        {
            var enumTypes = new[]
            {
                typeof(Skippy),
                typeof(Sparse),
                typeof(Negatives),
                typeof(DayOfWeek),
                typeof(FakeStatusCodes),
                typeof(Empty),
                typeof(FunWithFlags0),
                typeof(FunWithFlags1),
                typeof(FunWithFlags2),
                typeof(FunWithFlags3),
                typeof(FunWithFlags4),
                typeof(FunWithFlags5),
                typeof(FunWithFlags6),
            }
            .Concat(typeof(Util.CorEnums).GetNestedTypes())
            .ToList();

            var buffer            = new byte[256];
            var tiny2             = new byte[2];
            var tiny4             = new byte[4];
            var newtEnumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();
            var values            = Enumerable.Range(0, 256).Select(i => (ulong)i).ToArray();

            foreach (var enumType in enumTypes)
            {
                var lookup = StringEnum.GetCachedLookup(enumType);

                foreach (var value in values)
                {
                    var count = GetStringEnum(lookup, value, buffer, enumType);
                    Assert.True(count > 0, "Positive count expected");

                    if (count > tiny2.Length)
                    {
                        // just make sure it doesn't throw
                        GetStringEnum(lookup, value, tiny2, enumType);
                    }
                    if (count > tiny4.Length)
                    {
                        // just make sure it doesn't throw
                        GetStringEnum(lookup, value, tiny4, enumType);
                    }

                    if (buffer[0] == (byte)'"')
                    {
                        // string
                        Assert.True(count > 2, "Count > 2 expected");
                        var name        = Encoding.UTF8.GetString(buffer, 1, count - 2);
                        var parsedValue = Enum.Parse(enumType, name, ignoreCase: false);
                        Assert.Equal(value, ToUInt64(enumType, parsedValue));
                    }
                    else
                    {
                        var   number      = Encoding.UTF8.GetString(buffer, 0, count);
                        bool  signed      = IsSigned(enumType);
                        ulong parsedValue = signed ?
                                            (ulong)long.Parse(number, CultureInfo.InvariantCulture) :
                                            ulong.Parse(number, CultureInfo.InvariantCulture);
                        Assert.Equal(value, parsedValue);
                    }
                }
            }

            Assert.True(StringEnum.CachedLookups.Length >= enumTypes.Count, "All tested enum types should be cached");
            Assert.Equal(2, StringEnum.PagesAllocated);
        }